SlideShare a Scribd company logo
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

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
Sujit 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 Detection
DADAJONJURAKUZIEV
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
AshutoshTrivedi30
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
Christopher Haupt
 
Groupingobject
GroupingobjectGroupingobject
Groupingobject
Fajar Baskoro
 
JS for multidisciplinary teams
JS for multidisciplinary teamsJS for multidisciplinary teams
JS for multidisciplinary teams
Francisco Ferreira
 
3 class definition
3 class definition3 class definition
3 class definition
Robbie AkaChopa
 
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
Marc Bolaños Solà
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming Terminology
Michael Henson
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
Mumbai Academisc
 
About Python
About PythonAbout Python
About Python
Shao-Chuan Wang
 
Chap01
Chap01Chap01
Chap01
Jotham Gadot
 
Chapter08
Chapter08Chapter08
Chapter08
Robbie AkaChopa
 
[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
 
Building gui
Building guiBuilding gui
Building gui
Fajar Baskoro
 
Clustering_Overview.pptx
Clustering_Overview.pptxClustering_Overview.pptx
Clustering_Overview.pptx
nyomans1
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
mdfkhan625
 
The deep bootstrap framework review
The deep bootstrap framework reviewThe deep bootstrap framework review
The deep bootstrap framework review
taeseon ryu
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
 

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

Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Pemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdf
Pemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdfPemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdf
Pemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdf
Fajar Baskoro
 
Skills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptx
Skills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptxSkills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptx
Skills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptx
Fajar Baskoro
 
Slides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptx
Slides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptxSlides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptx
Slides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptx
Fajar Baskoro
 
PPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptx
PPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptxPPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptx
PPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptx
Fajar Baskoro
 
PPT-Menyiapkan Alumni GenerasiTerampil.pptx
PPT-Menyiapkan Alumni GenerasiTerampil.pptxPPT-Menyiapkan Alumni GenerasiTerampil.pptx
PPT-Menyiapkan Alumni GenerasiTerampil.pptx
Fajar Baskoro
 
RIngkasan Program - Markoding Innovation Challenge.pptx
RIngkasan Program - Markoding Innovation Challenge.pptxRIngkasan Program - Markoding Innovation Challenge.pptx
RIngkasan Program - Markoding Innovation Challenge.pptx
Fajar Baskoro
 
Pengembangan Program Pelatihan Double Track - DT PLUSK
Pengembangan Program Pelatihan Double Track - DT PLUSKPengembangan Program Pelatihan Double Track - DT PLUSK
Pengembangan Program Pelatihan Double Track - DT PLUSK
Fajar Baskoro
 
DT-PLUSK Pengembangan SMA Double Track Tahun ke 5
DT-PLUSK Pengembangan SMA Double Track Tahun ke 5DT-PLUSK Pengembangan SMA Double Track Tahun ke 5
DT-PLUSK Pengembangan SMA Double Track Tahun ke 5
Fajar Baskoro
 
Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptx
Fajar Baskoro
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarter
Fajar 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 Ramadhan
Fajar 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 KUS
Fajar 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.pptx
Fajar 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.pdf
Fajar 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.pptx
Fajar 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.pptx
Fajar Baskoro
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptx
Fajar 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 Kaltim
Fajar 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 sekolah
Fajar Baskoro
 

More from Fajar Baskoro (20)

Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Pemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdf
Pemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdfPemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdf
Pemberdayaan Kelompok Usaha Siswa dengan Tools Wirausaha AI.pdf
 
Skills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptx
Skills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptxSkills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptx
Skills for The Future - Pemberdayaan Remaja Untuk Meningkatkan Keterampilan.pptx
 
Slides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptx
Slides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptxSlides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptx
Slides OOSC - Program Penanganan ATS Unicef Bappeda Jawa Timur.pptx
 
PPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptx
PPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptxPPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptx
PPT- Menyiapkan GenerasiTerampilDigitalSkill1.pptx
 
PPT-Menyiapkan Alumni GenerasiTerampil.pptx
PPT-Menyiapkan Alumni GenerasiTerampil.pptxPPT-Menyiapkan Alumni GenerasiTerampil.pptx
PPT-Menyiapkan Alumni GenerasiTerampil.pptx
 
RIngkasan Program - Markoding Innovation Challenge.pptx
RIngkasan Program - Markoding Innovation Challenge.pptxRIngkasan Program - Markoding Innovation Challenge.pptx
RIngkasan Program - Markoding Innovation Challenge.pptx
 
Pengembangan Program Pelatihan Double Track - DT PLUSK
Pengembangan Program Pelatihan Double Track - DT PLUSKPengembangan Program Pelatihan Double Track - DT PLUSK
Pengembangan Program Pelatihan Double Track - DT PLUSK
 
DT-PLUSK Pengembangan SMA Double Track Tahun ke 5
DT-PLUSK Pengembangan SMA Double Track Tahun ke 5DT-PLUSK Pengembangan SMA Double Track Tahun ke 5
DT-PLUSK Pengembangan SMA Double Track Tahun ke 5
 
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
 

Recently uploaded

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
OnePlan Solutions
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 

Recently uploaded (20)

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 

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