SlideShare a Scribd company logo
1 of 24
Polimorphism
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
3Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The inheritance hierarchy
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
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.
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.
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
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?
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.
}}
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.
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?
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.
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.
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.
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.
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.
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);
}}
......
}}
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.
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.
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");
}}
}}
......
}}
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);
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.
23Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Access levels
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..

More Related Content

Similar to Polymorphism 9

Clustering_Overview.pptx
Clustering_Overview.pptxClustering_Overview.pptx
Clustering_Overview.pptx
nyomans1
 

Similar to Polymorphism 9 (20)

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
 
You Only Look Once: Unified, Real-Time Object Detection
You Only Look Once: Unified, Real-Time Object DetectionYou Only Look Once: Unified, Real-Time Object Detection
You Only Look Once: Unified, Real-Time Object Detection
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
Groupingobject
GroupingobjectGroupingobject
Groupingobject
 
JS for multidisciplinary teams
JS for multidisciplinary teamsJS for multidisciplinary teams
JS for multidisciplinary teams
 
3 class definition
3 class definition3 class definition
3 class definition
 
Object Discovery using CNN Features in Egocentric Videos
Object Discovery using CNN Features in Egocentric VideosObject Discovery using CNN Features in Egocentric Videos
Object Discovery using CNN Features in Egocentric Videos
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming Terminology
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
About Python
About PythonAbout Python
About Python
 
Chap01
Chap01Chap01
Chap01
 
Chapter08
Chapter08Chapter08
Chapter08
 
[CVPR 2018] Utilizing unlabeled or noisy labeled data (classification, detect...
[CVPR 2018] Utilizing unlabeled or noisy labeled data (classification, detect...[CVPR 2018] Utilizing unlabeled or noisy labeled data (classification, detect...
[CVPR 2018] Utilizing unlabeled or noisy labeled data (classification, detect...
 
Building gui
Building guiBuilding gui
Building gui
 
Clustering_Overview.pptx
Clustering_Overview.pptxClustering_Overview.pptx
Clustering_Overview.pptx
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
The deep bootstrap framework review
The deep bootstrap framework reviewThe deep bootstrap framework review
The deep bootstrap framework review
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 

More from Fajar Baskoro

Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
Fajar Baskoro
 

More from Fajar Baskoro (20)

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptx
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarter
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUS
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptx
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptx
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptx
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi Kaltim
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolah
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remaja
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
 
epl1.pdf
epl1.pdfepl1.pdf
epl1.pdf
 
user.docx
user.docxuser.docx
user.docx
 
Dtmart.pptx
Dtmart.pptxDtmart.pptx
Dtmart.pptx
 
DualTrack-2023.pptx
DualTrack-2023.pptxDualTrack-2023.pptx
DualTrack-2023.pptx
 
BADGE.pptx
BADGE.pptxBADGE.pptx
BADGE.pptx
 
womenatwork.pdf
womenatwork.pdfwomenatwork.pdf
womenatwork.pdf
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdf
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

Recently uploaded (20)

WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 

Polymorphism 9

  • 2. 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..