More Related Content Similar to Polymorphism 9 (20) More from Fajar Baskoro (20) Polymorphism 92. 2Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Main concepts to be covered
• method polymorphism
• static and dynamic type
• overriding
• dynamic method lookup
• protected access
3. 3Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The inheritance hierarchy
4. 4Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Conflicting output
CD: A Swingin' Affair (64 mins)*CD: A Swingin' Affair (64 mins)*
Frank SinatraFrank Sinatra
tracks: 16tracks: 16
my favourite Sinatra albummy favourite Sinatra album
DVD: O Brother, Where Art Thou? (106 mins)DVD: O Brother, Where Art Thou? (106 mins)
Joel & Ethan CoenJoel & Ethan Coen
The Coen brothers’ best movieThe Coen brothers’ best movie!!
title: A Swingin' Affair (64 mins)*title: A Swingin' Affair (64 mins)*
my favourite Sinatra albummy favourite Sinatra album
title:title: O Brother, Where Art Thou? (106 mins)O Brother, Where Art Thou? (106 mins)
The Coen brothers’ best movieThe Coen brothers’ best movie!!
What we wantWhat we want
What we haveWhat we have
5. 5Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The problem
• TheThe printprint method inmethod in ItemItem onlyonly
prints the common fields.prints the common fields.
• Inheritance is a one-way street:Inheritance is a one-way street:
– A subclass inherits the superclass fields.A subclass inherits the superclass fields.
– The superclass knows nothing about itsThe superclass knows nothing about its
subclass’s fields.subclass’s fields.
6. 6Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Attempting to solve the
problem
• Place print where it
has access to the
information it needs.
• Each subclass has its
own version.
• But Item’s fields are
private.
• Database cannot find
a print method in
Item.
7. 7Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Static type and dynamic type
• A more complex type hierarchy needs
further concepts to describe it.
• Some new terminology:
– static type
– dynamic type
– method dispatch/lookup
8. 8Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Static and dynamic type
Car c1 = new Car();What is the type of c1?
Vehicle v1 = new Car();What is the type of v1?
9. 9Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Static and dynamic type
• The declared type of a variable is itsThe declared type of a variable is its
static typestatic type..
• The type of the object a variableThe type of the object a variable
refers to is itsrefers to is its dynamic typedynamic type..
• The compiler’s job is to check forThe compiler’s job is to check for
static-typestatic-type violations.violations.
for(Item item : items) {for(Item item : items) {
item.print();item.print(); // Compile-time error.// Compile-time error.
}}
10. 10Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Overriding: the solution
print method
in both super-
and subclasses.
Satisfies both
static and
dynamic type
checking.
11. 11Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Overriding
• Superclass and subclass define
methods with the same signature.
• Each has access to the fields of its
class.
• Superclass satisfies static type check.
• Subclass method is called at runtime
– it overrides the superclass version.
• What becomes of the superclass
version?
12. 12Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Method lookup
No inheritance or polymorphism.
The obvious method is selected.
13. 13Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Method lookup
Inheritance but no
overriding. The inheritance
hierarchy is ascended,
searching for a match.
14. 14Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Method lookup
Polymorphism and
overriding. The ‘first’
version found is used.
15. 15Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Method lookup summary
• The variable is accessed.
• The object stored in the variable is found.
• The class of the object is found.
• The class is searched for a method match.
• If no match is found, the superclass is
searched.
• This is repeated until a match is found, or
the class hierarchy is exhausted.
• Overriding methods take precedence.
16. 16Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Super call in methods
• Overridden methods are hidden ...Overridden methods are hidden ...
• ... but we often still want to be able... but we often still want to be able
to call them.to call them.
• An overridden methodAn overridden method cancan be calledbe called
from the method that overrides it.from the method that overrides it.
– super.print (...)super.print (...)
– Compare with the use ofCompare with the use of supersuper inin
constructors.constructors.
17. 17Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Calling an overridden method
public class CD extends Itempublic class CD extends Item
{{
......
public void print ()public void print ()
{{
super.print ();super.print ();
System.out.println (" " + artist);System.out.println (" " + artist);
System.out.println (" tracks: " +System.out.println (" tracks: " +
numberOfTracks);numberOfTracks);
}}
......
}}
18. 18Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Method polymorphism
• We have been discussingWe have been discussing polymorphicpolymorphic
method dispatchmethod dispatch..
• A polymorphic variable can storeA polymorphic variable can store
objects of varying types.objects of varying types.
• Method calls areMethod calls are polymorphic..
– The actual method called depends onThe actual method called depends on
the dynamic object type.the dynamic object type.
19. 19Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The Object class’s methods
• Methods inMethods in ObjectObject are inherited byare inherited by
all classes.all classes.
• Any of these may be overridden.Any of these may be overridden.
• TheThe toStringtoString method (ofmethod (of ObjectObject))
is commonly overridden:is commonly overridden:
– public String toString ()public String toString ()
– Returns a string representation of theReturns a string representation of the
object.object.
20. 20Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Overriding toString
public class Itempublic class Item
{{
......
public String toString ()public String toString ()
{{
String line1 = title +String line1 = title +
" (" + playingTime + " mins)");" (" + playingTime + " mins)");
if (gotIt) {if (gotIt) {
return line1 + "*n" + " " +return line1 + "*n" + " " +
comment + "n");comment + "n");
} else {} else {
return line1 + "n" + " " +return line1 + "n" + " " +
comment + "n");comment + "n");
}}
}}
......
}}
21. 21Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Overriding toString
• ExplicitExplicit printprint methods can often bemethods can often be
omitted from a class:omitted from a class:
System.out.println (item.toString());System.out.println (item.toString());
• Calls toCalls to printlnprintln with just an objectwith just an object
automatically result inautomatically result in toStringtoString
being called:being called:
System.out.println (item);System.out.println (item);
22. 22Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Protected access
• Private access in the superclass may be tooPrivate access in the superclass may be too
restrictive for a subclass.restrictive for a subclass.
• The closer inheritance relationship isThe closer inheritance relationship is
supported bysupported by protected accessprotected access: protected: protected
things (fields, constructors, methods, etc.)things (fields, constructors, methods, etc.)
may be used by sub-classes.may be used by sub-classes.
• Protected access is more restricted thanProtected access is more restricted than
public access.public access.
• We still recommendWe still recommend keeping fields privatekeeping fields private..
– Define protected accessors and mutators forDefine protected accessors and mutators for
sub-classes to use.sub-classes to use.
23. 23Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Access levels
24. 24Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Review
• The declared type of a variable is itsThe declared type of a variable is its staticstatic
typetype::
– Compilers check static types.Compilers check static types.
• The type of an object is itsThe type of an object is its dynamic typedynamic type::
– Dynamic types are used at runtime.Dynamic types are used at runtime.
• Methods may beMethods may be overriddenoverridden in a subclass.in a subclass.
• Method lookup starts with theMethod lookup starts with the dynamicdynamic
typetype..
• ProtectedProtected access reflectsaccess reflects inheritanceinheritance..