Title: 159.234 Lecture 10
1159.234 LECTURE
29
JAVA
Inheritance, Polymorphism, and Interfaces
2Polymorphism
Polymorphism Interfaces reduce duplication in
programming effort
Immediate superclass
Parent class
subclass1
subclass2
subclass
subclass3
Object of different subclasses
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.
3Polymorphism
Polymorphism Interfaces reduce duplication in
programming effort
- Subclass
- inherits instance variables methods
(behaviours) - can add additional instance variables methods
- can override the behaviour of methods inherited
from its parent class.
Immediate superclass
ParentClass
p
SubClass
s
A subclass needs only to provide methods to
implement the differences between itself and its
parent.
p must actually refer to a SubClass object when
the program executes otherwise, Java will throw
a ClassCastException.
p s //s is upcast to its ParentClass
s p //illegal! Compile-time error!
s (SubClass) p //legal - downcast p into its
subclass type
4Java 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
5Fundamental 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
6- 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
7- 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 i0ilta.lengthi)
- summed ai
-
- 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
- gt java Overload
- Sum i 55
- Sum l 88
- Sum f 30.0
- Sum d 25.0
See Overload.java
8- 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)
-
- private int amount
- Constructors() // constructor
with no args - this(0, "empty")
-
- Constructors(String s) // four overloaded
constructor methods - this(0, s )
-
- Constructors(int i)
- 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
- gt java Constructors
- 0 empty
- 0 Label
- 42 empty
- gt
Calls on another Constructor of the same class
Calls on Constructor of parent class
9- 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() ) -
-
- class Legacy extends Object
- // the extends Object is redundant as all java
objects extend Object - // by default, unless they explicitly extend
some other class - private String legacy
- public void setlegacy( String something )
- legacy something
-
- public String getlegacy()
- Java Inheritance
- single inheritance (unlike C)
- subclass inherits variables and methods from
parent superclass - Example results
- gt java Inheritance
- i.toString() givesInheritance_at_18c4387
- i.getlegacy() gives money
- gt
Accessible only to the subclass through the
methods setlegacy() and getlegacy().
10- 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 ) - else if ( x instanceof Wolf )
- legcount ((Wolf)x).legs()
- Java Polymorphism
- superclass reference can contain subclass
references - casts possible
- Example results
- gt java Polymorph
- has higherBrain 3
- 2 legs
- Temperature 37.5
- has tail 4
- 4 legs
- Temperature 29.0
- gt
Downcasts Mammal x to Human
11- 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 )
- Java Abstract Classes
- No method body
- cannot be instantiated
- used to embody a design and partial code
- Example Output
- gt java Abstraction
- This conforms to the Design designation 3
- gt
Any class containing an abstract method, or
failing to override an abstract method inherited
from its superclass is an abstract class.
12Interfaces
may contain method signatures and constants
- 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, its should provide an
implementation for every abstract method in the
interface. The method should exactly have the
same argument definition.
13Interfaces
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.
14- 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
- 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 a promise
to provide the implied methods - Example output
- gt java Interfacial
- I conform
- gt
15- Inner Classes
- convenient to keep all relevant code local to the
file - also handy for 'hiding' code from use by other
classes - Example Output
- gt java Inner
- Local hero 45 78 16
- gt
- 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 -
-
-
See Inner.java
16- 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) )
-
-
- Anonymous Classes
- instantiated without a name
- useful for once-off interface compliance
- Example Output
- gt java Anonymous
- This is a message made from the int 42
- gt
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
accessable as the - // overridden method in
the superclass - return super.text() " though thou be thrice
times a fool" - // can still invoke
overridden method -
- class Parent
- public String message()
- return "I am thy father's spirit"
-
- 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
- gt java Override
- to be or not to be
- Verily, verily I say unto thee though thou be
thrice times a fool - gt
18- 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() )
-
- public static final double PI 3.141592654//
a constant - // String name() return "Corruption" //
this line would cause - //
a compiler error -
- class Note
- final String name() // cannot be overriden
- return "Ultimatum note"
-
- Final Modifier
- means class may not be extended
- means method cannot be overridden in a subclass
- means variable is a constant
- Example Output
- gt java Final
- 3.141592654 Ultimatum note
- gt
Static or private methods are automatically final.
Final class cannot be a superclass.
All methods in a final class are automatically
final.
Optimized by compiler
You may declare commonly used methods that do not
need to be inherited to be final.
19Java Access Modifiers - Accessible ?
20Modifiers effect on variables, methods classes
21Java packages
- //
- // Test Packages Example Program
- //
- import uwb.cast.
- public class TestPackages
- public static void main(String args)
- Packages.test() //
invoke the static method - Packages mypackage new Packages() //
instantiate class - mypackage.useless() //
invoke instance's method -
-
- package statement must be first statement in
source file - import the class into other code
- default case is to belong to anonymous package
- care needed to avoid interference effects if the
CLASSPATH and directories are not set up properly
- // Packages Example Program
- package uwb.cast
- public class Packages
- public static void main(String args)
- test() // invoke the
static method - Packages p new Packages() // instantiate
class - p.useless() // invoke
instance's method -
- public static void test()
- System.out.println("test method in class
uwb.cast.Package") -
- public void useless()
- System.out.println("useless method in class
uwb.cast.Package") -
Output gt ls src/ test/ uwb/ gt ls
src compile Packages.java gt cd test gt
ls TestPackages.class TestPackages.java gt java
Test TestPackages.class TestPackages.java gt
java TestPackages test method in class
uwb.cast.Package useless method in class
uwb.cast.Package
22Exercises
- Modify the Person class to be part of a package
called Personnel. - Compile your code and run your program. If
necessary adjust the CLASSPATH as necessary to
find the class files. - Create a class called driver that contains the
main() method copied from Person. Which
package(s) do you need to import? - Compile and run your code.
23- Create a subclass of Person called Employee. An
Employee has an extra field, Employer which is
also a String. Ensure the Employee is also part
of the Personnel package. - Experiment with adding new records into the
people array, both of type Person and Employee. - Compile and run your code.
- Create a further subclass of Employee called
Manager with suitable extra fields. - Compile and run your code.
24Summary
- Java has modifiers to support access
restrictions (encapsulation) and other common
ideas in OO programming
- Java has only single inheritance but has
abstract classes and interfaces to support
design ideas - Polymorphism works with object references