SlideShare a Scribd company logo
1 of 24
Polymorphism
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

What's hot

Programming Terminology
Programming TerminologyProgramming Terminology
Programming TerminologyMichael Henson
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Jim Driscoll
 
Session 05 - Strings in Java
Session 05 - Strings in JavaSession 05 - Strings in Java
Session 05 - Strings in JavaPawanMM
 
Smalltalk on the JVM
Smalltalk on the JVMSmalltalk on the JVM
Smalltalk on the JVMESUG
 
Function-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScriptFunction-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScriptHong Langford
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2Mudasir Syed
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Java 102 intro to object-oriented programming in java - exercises
Java 102   intro to object-oriented programming in java - exercisesJava 102   intro to object-oriented programming in java - exercises
Java 102 intro to object-oriented programming in java - exercisesagorolabs
 
Jaxb unmarshal xml to pojo tutorialspoint examples
Jaxb unmarshal   xml to pojo   tutorialspoint examplesJaxb unmarshal   xml to pojo   tutorialspoint examples
Jaxb unmarshal xml to pojo tutorialspoint examplesbeginners tutorial
 
Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 
Session 01 - Introduction to Java
Session 01 - Introduction to JavaSession 01 - Introduction to Java
Session 01 - Introduction to JavaPawanMM
 
Debugging Your Production JVM
Debugging Your Production JVMDebugging Your Production JVM
Debugging Your Production JVMkensipe
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemLeonard Axelsson
 

What's hot (20)

Sep 15
Sep 15Sep 15
Sep 15
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 
java review
java reviewjava review
java review
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming Terminology
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Session 05 - Strings in Java
Session 05 - Strings in JavaSession 05 - Strings in Java
Session 05 - Strings in Java
 
Smalltalk on the JVM
Smalltalk on the JVMSmalltalk on the JVM
Smalltalk on the JVM
 
Object Class
Object Class Object Class
Object Class
 
Function-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScriptFunction-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScript
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2
 
04 sorting
04 sorting04 sorting
04 sorting
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Java 102 intro to object-oriented programming in java - exercises
Java 102   intro to object-oriented programming in java - exercisesJava 102   intro to object-oriented programming in java - exercises
Java 102 intro to object-oriented programming in java - exercises
 
Jaxb unmarshal xml to pojo tutorialspoint examples
Jaxb unmarshal   xml to pojo   tutorialspoint examplesJaxb unmarshal   xml to pojo   tutorialspoint examples
Jaxb unmarshal xml to pojo tutorialspoint examples
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
Java Day-1
Java Day-1Java Day-1
Java Day-1
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Session 01 - Introduction to Java
Session 01 - Introduction to JavaSession 01 - Introduction to Java
Session 01 - Introduction to Java
 
Debugging Your Production JVM
Debugging Your Production JVMDebugging Your Production JVM
Debugging Your Production JVM
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy Ecosystem
 

Similar to Polymorphism 9

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with javaSujit Kumar
 
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 DetectionDADAJONJURAKUZIEV
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxethiouniverse
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Christopher Haupt
 
JS for multidisciplinary teams
JS for multidisciplinary teamsJS for multidisciplinary teams
JS for multidisciplinary teamsFrancisco Ferreira
 
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 VideosMarc Bolaños Solà
 
[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...NAVER Engineering
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
Clustering_Overview.pptx
Clustering_Overview.pptxClustering_Overview.pptx
Clustering_Overview.pptxnyomans1
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 
The deep bootstrap framework review
The deep bootstrap framework reviewThe deep bootstrap framework review
The deep bootstrap framework reviewtaeseon ryu
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scopingPatrick Sheridan
 

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)
 
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
 
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...
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Clustering_Overview.pptx
Clustering_Overview.pptxClustering_Overview.pptx
Clustering_Overview.pptx
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
The deep bootstrap framework review
The deep bootstrap framework reviewThe deep bootstrap framework review
The deep bootstrap framework review
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
OOP in JS
OOP in JSOOP in JS
OOP in JS
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 

More from Fajar Baskoro

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxFajar Baskoro
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterFajar Baskoro
 
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 RamadhanFajar Baskoro
 
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 KUSFajar Baskoro
 
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.pptxFajar Baskoro
 
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.pdfFajar Baskoro
 
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.pptxFajar Baskoro
 
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.pptxFajar Baskoro
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxFajar Baskoro
 
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 KaltimFajar Baskoro
 
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 sekolahFajar Baskoro
 
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 remajaFajar Baskoro
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetFajar Baskoro
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdfFajar 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

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 

Recently uploaded (20)

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 

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