Transcript Lecture

159.234 LECTURE
25
JAVA-3
Inheritance, Polymorphism, and Interfaces
1
Polymorphism
Polymorphism + Interfaces = reduce duplication in programming effort
Immediate superclass
Parent class
subclass1
subclass2
Object of different
subclasses subclass3
subclass1
subclass2
subclass
subclass3
subclass = derived class
Treat them as a single unit by
referring to them as objects of
their common superclass.
Java is able to automatically apply the proper methods to each
object, regardless of the subclass the object came from.
2
Polymorphism
Polymorphism + Interfaces = reduce duplication in programming effort
Immediate superclass
p
ParentClass
s
SubClass
Subclass
• inherits instance variables & methods (behaviours)
• can add additional instance variables & methods
• can override the behaviour of methods inherited
from its parent class.
* A subclass needs only to provide methods to
implement the differences between itself and its parent.
p = s; //s is upcast to its ParentClass
s = p; //illegal! Compile-time error!
p must actually refer to a SubClass
object when the program executes;
otherwise, Java will throw a
ClassCastException.
s = (SubClass) p ; //legal - downcast p into its subclass type
3
Java Classes and Objects
•
•
•
•
•
•
•
•
•
•
•
Java Object Fundamentals
Method Overloading
Constructor Methods
Inheritance
Polymorphism
Abstract Classes
Interfaces
Inner Classes & Anonymous Classes
Overriding Methods
Final Modifier
Java Modifiers Summary
4
Fundamental Ideas
•
•
•
•
•
•
•
•
•
data fields & methods
Functions (methods) arguments pass-by-value
this, super - references to current object & parent
data hiding and encapsulation
overloading method names
construction and initialisation and default constructor
sub-classing, instanceof and polymorphism
single inheritance and non inheritance of constructors
casts up and down class hierarchies
See Examples
5
• overriding methods and accessing overridden methods
using super
• overloaded constructors
• parent class constructors
• class variables and methods - static
• final - class (non extensible) final methods (not
• override-able), final variables (constants)
• abstract classes & interfaces
• access modifiers
• inner classes & anonymous classes
• package grouping mechanism and import
6
public class Overload{
public static void main( String args[] ) {
int i[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
long l[] = { 1, 1, 2, 3, 5, 8, 13, 21, 34 };
float f[] = { 0.0F, 2.0F, 4.0F, 6.0F, 8.0F, 10.0F };
double d[] = { 1.0, 3.0, 5.0, 7.0, 9.0 };
System.out.println("Sum i = " + sum( i ) );
System.out.println("Sum l = " + sum( l ) );
System.out.println("Sum f = " + sum( f ) );
System.out.println("Sum d = " + sum( d ) );
}
public static long sum( int[] a ){
long summed = 0L;
for(int i=0;i<a.length;i++){
summed += a[i];
}
return summed;
}
public static long sum( long[] a ){
long summed = 0L;
for(int i=0;i<a.length;i++){
summed += a[i];
}
return summed;
}
public static double sum( float[] a ){
double summed = 0.0;
for(int i=0;i<a.length;i++){
summed += a[i];
}
return summed;
}
public static double sum( double[] a ){
double summed = 0.0;
for(int i=0;i < a.length; i++){
summed += a[i];
}
return summed;
}
}
Java allows several methods to be defined with the same name, as
long as the methods have different sets of parameters (based
on the number, types, and order of the parameters).
• Method Overloading
– overload methods with different
args and return types
– return type must not be the only
distinction
– There is no operator overloading in
Java
• Example Output:
> java Overload
Sum i = 55
Sum l = 88
Sum f = 30.0
Sum d = 25.0
7
See Overload.java
public class Constructors extends Worker{
public static void main( String args[] ) {
Constructors a = new Constructors();
Constructors b = new Constructors("Label");
Constructors c = new Constructors(42);
Constructors d = new Constructors(36,"Full");
System.out.println(a.amount + " " + a.label);
System.out.println(b.amount + " " + b.label);
System.out.println(c.amount + " " + c.label);
System.out.println(d.amount + " " + d.label);
}
private int amount;
Constructors(){
// constructor with no args
this(0, "empty");
}
Constructors(String s){
// four overloaded
constructor methods
this(0, s );
}
Constructors(int i){
this(i, "empty");
}
Constructors( int i, String s ){
super( s );
amount = i;
}
}
class Worker{
String label;
// default protection, so that
// theConstructors class inherits it
Worker( String str ){ // a single constructor method
with an arg
label = str;
}
}
•
Constructor Methods
–
–
–
–
–
–
–
–
•
do not inherit constructor
system supplied constructor takes no arguments
once overridden lose the use of the system supplied constructor
can overload constructor
can access other constructors using this()
access parent's constructor using super()
only one level of indirection allowed (no super.super() allowed )
Destruction is automatically done using garbage collection by the system.
Example Output:
> java Constructors
0 empty
0 Label
42 empty
36 Full
>
Calls on another
Constructor of the
same class
Calls on Constructor
of parent class
8
public class Inheritance extends Legacy{
public static void main(String args[]){
Inheritance i = new Inheritance();
System.out.println("i.toString() gives: " + i.toString() );
// toString() inherited from java.lang.Object
i.setLegacy("money"); // set/getLegacy inherited from Legacy
System.out.println("i.getLegacy() gives: " + i.getLegacy() );
}
This is redundant as all java
}
objects extend Object by default,
unless they explicitly extend some
other class.
class Legacy extends Object{
private String legacy;
public void setLegacy( String something ){
legacy = something;
}
public String getLegacy(){
return legacy;
Accessible only to the
}
subclass through the
}
• Java Inheritance
– single inheritance
(unlike C++)
– subclass inherits
variables and methods
from parent superclass
• Example results:
> java Inheritance
i.toString()
gives:Inheritance@18c4387
i.getlegacy() gives: money
>
methods setlegacy()
and getlegacy().
This is giving us some numeric
value because the class
Inheritance did not implement the
method toString()
9
public class Polymorph{
public static void main( String args[] ) {
Mammal m;
Human h = new Human();
Wolf w = new Wolf();
m = h;
Mammal.describe(m);
m = w;
Mammal.describe(m);
}
}
class Mammal{
public static void describe(Mammal x){
int legcount;
if( x instanceof Human ){
legcount = ((Human)x).legs();
System.out.println("has higherBrain " + ((Human)x).higherBrain );
Downcasts Mammal x
to Human
}else if ( x instanceof Wolf ){
legcount = ((Wolf)x).legs();
System.out.println("has tail " + ((Wolf)x).tail );
}else{
legcount = 0;
}
System.out.println(legcount + " legs" );
System.out.println("Temperature " + x.temperature );
}
double temperature = 0.0; //defaults to package access, therefore visible in it’s sublclasses
}
class Human extends Mammal{
public int higherBrain = 3; //data member
Human(){ temperature = 37.5; } //constructor
public int legs(){ return 2; } //method
}
class Wolf extends Mammal{
public int tail = 4; //data member
Wolf(){ temperature = 29.0; } //constructor
public int legs(){ return 4; } //method
}
• Java Polymorphism
– superclass reference can
contain subclass
references
– casts possible
• Example results:
> java Polymorph
has higherBrain 3
2 legs
Temperature 37.5
has tail 4
4 legs
Temperature 29.0
>
10
public class Abstraction extends Design{
public static void main(String args[] ){
// Design d = new Design(); // not allowed to instantiate an
// abstract class
Abstraction a = new Abstraction();
a.start(1);
a.stop(2);
System.out.println(a.description());
}
public void start(int x){ // must provide start and stop
state = x;
// or Abstraction will also be abstract
}
public void stop(int z){
state += z;
}
}
abstract class Design{
public abstract void start( int x );
public abstract void stop( int y );
protected int state = 0;
public String description(){
return "This conforms to the Design designation: " + state;
}
}
• Java Abstract Classes
– No method body
– cannot be instantiated
– used to embody a design
and partial code
• Example Output:
> java Abstraction
This conforms to the Design designation: 3
>
*Any class containing an abstract method, or failing
to override an abstract method inherited from its
superclass is an abstract class.
This is required!
11
Interfaces
may contain method signatures and constants
Interface
Abstract class
subclass1
subclass2
Class 3
Class 4
• has no direct inherited relationship with any particular class; they are
defined independently
• any class may choose to implement an interface by adding an
implements clause to its class definition. If so, it should provide an
implementation for every abstract method in the interface. The method
should have exactly the same argument definition.
12
Interfaces
may contain method signatures and constants
• use interfaces to create the same standard method definitions in many
different classes. This will enable you to write a single method (e.g. sort,
search, etc.) to manipulate all of the classes that implement the interface.
13
public class Interfacial implements Template, Template2{
private int state = 0;
public static void main(String args[] ){
Interfacial i = new Interfacial();
Template t = i;
t.start(1); t.stop(2);
Template2 t2 = i;
System.out.println( t2.description() );
}
public void start(int x){ // must provide start, stop & description
state = x;
// or compiler will flag non compliance
}
// to interface spec
public void stop(int z){
state += z;
}
public String description(){ return "I conform"; }
}
// the interfaces would normally be in some other file and probably
// have been written by someone else at some other time
interface Template{
public void start( int x );// these abstract methods must have no body
public void stop( int y ); // no member variables allowed in interface
}
interface Template2{
public String description();
}
• Java Interfaces
– like abstract classes but no bodies or
variables, except constants
– used for interface specification -equivalent to a C header file
– classes can implement as many
interfaces as desired
– compiler will flag any non-compliance
with interface specification
– implements interface is a bit like of a
“promise” to provide the implied
methods
• Example output:
> java Interfacial
I conform
>
14
Interfaces
Class that implements two interfaces
interface TargetPursuit{
public boolean targetDestroyed(int x, int y);
public int distance(int x, int y);
}
interface ObstacleAvoidance{
public boolean safeDistance();
public void findObstacles();
}
public class Robot{
protected void initialize(){
//Codes for initialize
}
protected void switchRole(){
//Codes for switchRole
}
protected void retreat(){
//Codes for retreat
}
}
public class Attacker extends Robot
implements TargetPursuit,
ObstacleAvoidance {
// Code here does something 15
}
public class Inner{
private static int state = 79;
public static void main(String args[]){
Inner i = new Inner();
i.doit();
}
public void doit(){
Local l = new Local();
l.code = 45; // can access because Local is a member
System.out.println( l.hero() );
}
public class Local extends Outer{
private int code = 33;
public String hero(){
state = 78;
return "Local hero " + code + " " + state + " " + space;
}
}
} //end of class Inner
class Outer{
protected int space = 16; // accessible to subclasses
}
• Inner Classes
– convenient to keep all
relevant code local to the
file
– also handy for 'hiding'
code from use by other
classes
• Example Output:
> java Inner
Local hero 45 78 16
>
This is not allowed in C++! You
cannot initialise a data member
not unless it is constant
16
See Inner.java
• Anonymous Classes
public class Anonymous{
public static void main(String args[]){
Anonymous a = new Anonymous();
a.doit();
}
public void doit(){
extract( new Dummy(){ // invokes extract() with an object of no name
public String message( int z ){
return "This is a message made from the int " + z;
}
} ); // parenthesis matches that next to extract above
}
public void extract(Dummy d ){
System.out.println( d.message(42) );
}
– instantiated without a
name
– useful for one-off
interface compliance
• Example Output:
> java Anonymous
This is a message made
from the int 42
>
}
interface Dummy{
public String message(int x);
}
17
public class Override extends Parent{
public static void main(String args[]){
Override o = new Override();
System.out.println(o.message() );
System.out.println(o.text() );
}
public String message(){// overrides the superclass's method
return "to be or not to be";
}
public String text(){ // must be at least as accessible as the
// overridden method in the superclass
return super.text() + " though thou be thrice times a fool";
}
// can still invoke overridden method
} //end of class Override
class Parent{
public String message(){
return "I am thy father's spirit";
}
protected String text(){// accesible from same package or any subclass
return "Verily, verily I say unto thee";
}
}
• Overriding Methods
– You can customise methods
otherwise inherited from
superclass
– overriding method must be
at least as accessible as
overridden method (unlike
in C++)
• Example Output:
> java Override
to be or not to be
Verily, verily I say unto thee though thou be thrice times a fool
>
18
• Final Modifier
public final class Final extends Note{
public static void main(String args[]){
Final o = new Final();
// PI = 4.2; // this line would cause compiler error
System.out.println( PI + " " + o.name() );
}
// a constant
public static final double PI = 3.141592654;
// String name() { return "Corruption"; }
//this line would cause a compiler error
}
class Note{
final String name(){ // cannot be overridden
return "Ultimatum note";
}
}
Optimized by compiler
– means class may not be
extended
– means method cannot be
overridden in a subclass
– means variable is a constant
• Example Output:
> java Final
3.141592654 Ultimatum note
>
Static or private methods are automatically final.
Final class cannot be a superclass.
All methods in a final class are automatically final.
You may declare commonly used methods that do
19
not need to be inherited to be final.
Summary
• Java has only single inheritance • Java has modifiers to
support access
but has abstract classes and
restrictions
interfaces to support design ideas
(encapsulation) and
• Polymorphism works with object
other
common
ideas
references
in OO programming
20