SlideShare a Scribd company logo
1 of 28
ProgrammingWithJava
ICS201
1
Chapter 8
Polymorphism
ProgrammingWithJava
ICS201 Object-Oriented Concept
 Object & Class
 Encapsulation
 Inheritance
 Polymorphism
2
ProgrammingWithJava
ICS201
3
Polymorphism
 polymorphism: many forms
ProgrammingWithJava
ICS201
4
Polymorphism
 Polymorphism (from the Greek, meaning "many
forms", or something similar)
 The mechanism by which several methods can have the
same name and implement the same abstract
operation.
 Requires that there be multiple methods of the
same name
 The choice of which one to execute depends on the
object that is in a variable
 Reduces the need for programmers to code many if-
else or switch statements
ProgrammingWithJava
ICS201 Polymorphism
DrawChart
DrawChart(1)
DrawChart(1,2,1,2)
DrawChart(1,1,1)
DrawTriangle(1,1,1)
DrawRect(1,2,1,2)
DrawCircle(1)
5
ProgrammingWithJava
ICS201
6
Polymorphism Example
ProgrammingWithJava
ICS201 Polymorphism
 Add(integer, integer)
 Add(string, string)
 Add(string, integer)
 Add(1,1)  2
 Add(“Hello”, “World”) 
“HelloWorld”
 Add(“Hello”, 2)  “Hello2”
ProgrammingWithJava
ICS201 Polymorphism
:PaySlip
:HourlyPaidEmployee
:WeeklyPaidEmployee
:MonthlyPaidEmployee

getTotalPay()
calculatePay()
calculatePay()
calculatePay()
8
ProgrammingWithJava
ICS201
Which bill() version ?
Which bill() version ?
Which bill() versions ?
Introductory example to Polymorphism
ProgrammingWithJava
ICS201
10
Polymorphism
 Methods can be overloaded. A method has the same
name as another member methods, but the type and/or
the count of parameters differs.
class Integer
{
float val;
void add( int amount )
{
val = val + amount;
}
void add( int num, int den)
{
val = float(num) / den;
}
}
ProgrammingWithJava
ICS201
11
Polymorphism
 Polymorphism is the ability to associate many meanings
to one method name
 It does this through a special mechanism known as
late binding or dynamic binding
 Inheritance allows a base class to be defined, and other
classes derived from it
 Code for the base class can then be used for its own
objects, as well as objects of any derived classes
 Polymorphism allows changes to be made to method
definitions in the derived classes.
ProgrammingWithJava
ICS201
12
Late Binding
 The process of associating a method definition with a
method invocation is called binding.
 If the method definition is associated with its call when
the code is compiled, that is called early binding.
 If the method definition is associated with its call when
the method is invoked (at run time), that is called late
binding or dynamic binding.
ProgrammingWithJava
ICS201
13
The Sale and DiscountSale Classes
 The Sale class contains two instance variables
 name: the name of an item (String)
 price: the price of an item (double)
 It contains two constructors
 A no-argument constructor that sets name to "No
name yet", and price to 0.0
 A two-parameter constructor that takes in a String
(for name) and a double (for price)
ProgrammingWithJava
ICS201
14
The Sale and DiscountSale Classes
 The Sale class also has
 a set of accessors (getName, getPrice),
 mutators (setName, setPrice),
 overridden methods equals and toString
 a static announcement method.
 a method bill, that determines the bill for a sale, which
simply returns the price of the item.
 It has also two methods, equalDeals and lessThan,
each of which compares two sale objects by comparing
their bills and returns a boolean value.
ProgrammingWithJava
ICS201
15
The Sale and DiscountSale Classes
 The DiscountSale class inherits the instance variables and
methods from the Sale class.
 In addition, it has its own instance variable, discount (a
percent of the price),
 it has also its own suitable constructor methods,
 accessor method (getDiscount),
 mutator method (setDiscount),
 overriden toString method, and static announcement
method.
 It has also its own bill method which computes the bill as a
function of the discount and the price.
ProgrammingWithJava
ICS201The Sale and DiscountSale Classes
 The Sale class lessThan method
 Note the bill() method invocations:
public boolean lessThan (Sale otherSale)
{
if (otherSale == null)
{
System.out.println("Error:null object");
System.exit(0);
}
return (bill( ) < otherSale.bill( ));
}
ProgrammingWithJava
ICS201The Sale and DiscountSale Classes
 The Sale class bill() method:
public double bill( )
{
return price;
}
 The DiscountSale class bill() method:
public double bill( )
{
double fraction = discount/100;
return (1 - fraction) * getPrice( );
}
ProgrammingWithJava
ICS201
18
The Sale and DiscountSale Classes
 Given the following in a program:
. . .
Sale simple = new sale(“xx", 10.00);
DiscountSale discount = new DiscountSale(“xx", 11.00, 10);
. . .
if (discount.lessThan(simple))
System.out.println("$" + discount.bill() +
" < " + "$" + simple.bill() +
" because late-binding works!");
. . .
 Output would be:
$9.90 < $10 because late-binding works!
ProgrammingWithJava
ICS201
19
The Sale and DiscountSale Classes
 In the previous example, the boolean expression in the if
statement returns true.
 As the output indicates, when the lessThan method in
the Sale class is executed, it knows which bill() method
to invoke
 The DiscountSale class bill() method for discount,
and the Sale class bill() method for simple.
 Note that when the Sale class was created and compiled,
the DiscountSale class and its bill() method did not yet
exist
 These results are made possible by late-binding
ProgrammingWithJava
ICS201
20
The final Modifier
 A method marked final indicates that it cannot be
overridden with a new definition in a derived class
 If final, the compiler can use early binding with the
method
public final void someMethod() { . . . }
 A class marked final indicates that it cannot be used as a
base class from which to derive any other classes
ProgrammingWithJava
ICS201
21
Upcasting and Downcasting
 Upcasting is when an object of a derived class is assigned
to a variable of a base class (or any ancestor class):
Example:
class Shape {
int xpos, ypos ;
public Shape(int x , int y){
xpos = x ;
ypos = y ;
}
public void Draw() {
System.out.println("Draw method called of class Shape") ;
}
}
ProgrammingWithJava
ICS201
22
Upcasting and Downcasting
class Circle extends Shape {
int r ;
public Circle(int x1 , int y1 , int r1){
super(x1 , y1) ;
r = r1 ;
}
public void Draw() {
System.out.println("Draw method called of class Circle") ;
}
}
class UpcastingDemo {
public static void main (String [] args) {
Shape s = new Circle(10 , 20 , 4) ;
s.Draw() ;
}
}
Output:
Draw method called of class Circle
ProgrammingWithJava
ICS201
23
Upcasting and Downcasting
 When we wrote Shape S = new Circle(10 , 20 , 4), we
have cast Circle to the type Shape.
 This is possible because Circle has been derived from Shape
 From Circle, we are moving up to the object hierarchy to
the type Shape, so we are casting our object “upwards” to
its parent type.
ProgrammingWithJava
ICS201
24
Upcasting and Downcasting
 Downcasting is when a type cast is performed from a
base class to a derived class (or from any ancestor class
to any descendent class).
Example:
class Shape {
int xpos, ypos ;
public Shape(int x , int y){
xpos = x ;
ypos = y ;
}
public void Draw() {
System.out.println("Draw method called of class Shape") ;
}
}
ProgrammingWithJava
ICS201
25
Upcasting and Downcasting
class Circle extends Shape {
int r ;
public Circle(int x1 , int y1 , int r1){
super(x1 , y1) ;
r = r1 ;
}
public void Draw() {
System.out.println("Draw method called of class Circle") ;
}
public void Surface() {
System.out.println("The surface of the circle is " +
((Math.PI)*r*r));
}
}
ProgrammingWithJava
ICS201
26
Upcasting and Downcasting
class DowncastingDemo {
public static void main (String [] args) {
Shape s = new Circle(10 , 20 , 4) ;
((Circle) s).Surface() ;
}
}
Output:
The surface of the circle is 50.26
ProgrammingWithJava
ICS201
27
Upcasting and Downcasting
 When we wrote Shape s = new Circle(10 , 20 , 4) we have
cast Circle to the type shape.
 In that case, we are only able to use methods found in
Shape, that is, Circle has inherited all the properties and
methods of Shape.
 If we want to call Surface() method, we need to down-
cast our type to Circle. In this case, we will move down
the object hierarchy from Shape to Circle :
 ((Circle) s).Surface() ;
ProgrammingWithJava
ICS201
28
Downcasting
 It is the responsibility of the programmer to use
downcasting only in situations where it makes sense
 The compiler does not check to see if downcasting is a
reasonable thing to do
 Using downcasting in a situation that does not make sense
usually results in a run-time error.

More Related Content

What's hot

Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Palak Sanghani
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continuedRatnaJava
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88Mahmoud Samir Fayed
 
Simple Scala DSLs
Simple Scala DSLsSimple Scala DSLs
Simple Scala DSLslinxbetter
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31Mahmoud Samir Fayed
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30myrajendra
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 

What's hot (16)

Op ps
Op psOp ps
Op ps
 
Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
 
08slide
08slide08slide
08slide
 
Simple Scala DSLs
Simple Scala DSLsSimple Scala DSLs
Simple Scala DSLs
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30
 
11slide
11slide11slide
11slide
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 

Viewers also liked

Strategie_workshop
Strategie_workshopStrategie_workshop
Strategie_workshopJan Bízik
 
Declaration local
Declaration local Declaration local
Declaration local Marine Bac
 
VishwasVats_MHRM_IITKGP
VishwasVats_MHRM_IITKGPVishwasVats_MHRM_IITKGP
VishwasVats_MHRM_IITKGPVishwas Vats
 
Personal narrative essay
Personal narrative essayPersonal narrative essay
Personal narrative essayDakota Heims
 
Behaviour driven development
Behaviour driven developmentBehaviour driven development
Behaviour driven developmentTony Nguyen
 
Data mining maximumlikelihood
Data mining maximumlikelihoodData mining maximumlikelihood
Data mining maximumlikelihoodTony Nguyen
 
Sr Presentation 2
Sr Presentation 2Sr Presentation 2
Sr Presentation 2guestd2364f
 
Permenkes No -2349-organisasi- BBTKL - PP
Permenkes No -2349-organisasi- BBTKL - PPPermenkes No -2349-organisasi- BBTKL - PP
Permenkes No -2349-organisasi- BBTKL - PPDitjen P2P
 
Writing an effective conclusion
Writing an effective conclusionWriting an effective conclusion
Writing an effective conclusionketurahhaferkamp
 
Lec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- Coherence
Lec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- CoherenceLec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- Coherence
Lec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- CoherenceHsien-Hsin Sean Lee, Ph.D.
 

Viewers also liked (16)

Drive Your Career
Drive Your CareerDrive Your Career
Drive Your Career
 
Presentación
PresentaciónPresentación
Presentación
 
Strategie_workshop
Strategie_workshopStrategie_workshop
Strategie_workshop
 
Declaration local
Declaration local Declaration local
Declaration local
 
VishwasVats_MHRM_IITKGP
VishwasVats_MHRM_IITKGPVishwasVats_MHRM_IITKGP
VishwasVats_MHRM_IITKGP
 
lkh iohoih
lkh iohoihlkh iohoih
lkh iohoih
 
Personal narrative essay
Personal narrative essayPersonal narrative essay
Personal narrative essay
 
161105+Amro+Letter
161105+Amro+Letter161105+Amro+Letter
161105+Amro+Letter
 
Behaviour driven development
Behaviour driven developmentBehaviour driven development
Behaviour driven development
 
Data mining maximumlikelihood
Data mining maximumlikelihoodData mining maximumlikelihood
Data mining maximumlikelihood
 
Sr Presentation 2
Sr Presentation 2Sr Presentation 2
Sr Presentation 2
 
Engrish
EngrishEngrish
Engrish
 
Permenkes No -2349-organisasi- BBTKL - PP
Permenkes No -2349-organisasi- BBTKL - PPPermenkes No -2349-organisasi- BBTKL - PP
Permenkes No -2349-organisasi- BBTKL - PP
 
Writing an effective conclusion
Writing an effective conclusionWriting an effective conclusion
Writing an effective conclusion
 
Abbott_Kinase
Abbott_KinaseAbbott_Kinase
Abbott_Kinase
 
Lec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- Coherence
Lec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- CoherenceLec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- Coherence
Lec14 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech --- Coherence
 

Similar to Java Polymorphism Chapter from ProgrammingWithJava Textbook

Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programmingDavid Giard
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docxCSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docxfaithxdunce63732
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphismUsama Malik
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 

Similar to Java Polymorphism Chapter from ProgrammingWithJava Textbook (20)

Refactoring Chapter11
Refactoring Chapter11Refactoring Chapter11
Refactoring Chapter11
 
basic concepts
basic conceptsbasic concepts
basic concepts
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
Chap08
Chap08Chap08
Chap08
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Java interface
Java interfaceJava interface
Java interface
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docxCSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Inheritance and-polymorphism
Inheritance and-polymorphismInheritance and-polymorphism
Inheritance and-polymorphism
 
Uta005
Uta005Uta005
Uta005
 
Object and class
Object and classObject and class
Object and class
 
Java class
Java classJava class
Java class
 
Java unit2
Java unit2Java unit2
Java unit2
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 

More from Fraboni Ec

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreadingFraboni Ec
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreadingFraboni Ec
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceFraboni Ec
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningFraboni Ec
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningFraboni Ec
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryFraboni Ec
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksFraboni Ec
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheFraboni Ec
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsFraboni Ec
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonFraboni Ec
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesFraboni Ec
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsFraboni Ec
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileFraboni Ec
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisFraboni Ec
 
Abstract class
Abstract classAbstract class
Abstract classFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 

More from Fraboni Ec (20)

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
 
Lisp
LispLisp
Lisp
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreading
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Abstract class
Abstract classAbstract class
Abstract class
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 

Recently uploaded (20)

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 

Java Polymorphism Chapter from ProgrammingWithJava Textbook

  • 2. ProgrammingWithJava ICS201 Object-Oriented Concept  Object & Class  Encapsulation  Inheritance  Polymorphism 2
  • 4. ProgrammingWithJava ICS201 4 Polymorphism  Polymorphism (from the Greek, meaning "many forms", or something similar)  The mechanism by which several methods can have the same name and implement the same abstract operation.  Requires that there be multiple methods of the same name  The choice of which one to execute depends on the object that is in a variable  Reduces the need for programmers to code many if- else or switch statements
  • 7. ProgrammingWithJava ICS201 Polymorphism  Add(integer, integer)  Add(string, string)  Add(string, integer)  Add(1,1)  2  Add(“Hello”, “World”)  “HelloWorld”  Add(“Hello”, 2)  “Hello2”
  • 9. ProgrammingWithJava ICS201 Which bill() version ? Which bill() version ? Which bill() versions ? Introductory example to Polymorphism
  • 10. ProgrammingWithJava ICS201 10 Polymorphism  Methods can be overloaded. A method has the same name as another member methods, but the type and/or the count of parameters differs. class Integer { float val; void add( int amount ) { val = val + amount; } void add( int num, int den) { val = float(num) / den; } }
  • 11. ProgrammingWithJava ICS201 11 Polymorphism  Polymorphism is the ability to associate many meanings to one method name  It does this through a special mechanism known as late binding or dynamic binding  Inheritance allows a base class to be defined, and other classes derived from it  Code for the base class can then be used for its own objects, as well as objects of any derived classes  Polymorphism allows changes to be made to method definitions in the derived classes.
  • 12. ProgrammingWithJava ICS201 12 Late Binding  The process of associating a method definition with a method invocation is called binding.  If the method definition is associated with its call when the code is compiled, that is called early binding.  If the method definition is associated with its call when the method is invoked (at run time), that is called late binding or dynamic binding.
  • 13. ProgrammingWithJava ICS201 13 The Sale and DiscountSale Classes  The Sale class contains two instance variables  name: the name of an item (String)  price: the price of an item (double)  It contains two constructors  A no-argument constructor that sets name to "No name yet", and price to 0.0  A two-parameter constructor that takes in a String (for name) and a double (for price)
  • 14. ProgrammingWithJava ICS201 14 The Sale and DiscountSale Classes  The Sale class also has  a set of accessors (getName, getPrice),  mutators (setName, setPrice),  overridden methods equals and toString  a static announcement method.  a method bill, that determines the bill for a sale, which simply returns the price of the item.  It has also two methods, equalDeals and lessThan, each of which compares two sale objects by comparing their bills and returns a boolean value.
  • 15. ProgrammingWithJava ICS201 15 The Sale and DiscountSale Classes  The DiscountSale class inherits the instance variables and methods from the Sale class.  In addition, it has its own instance variable, discount (a percent of the price),  it has also its own suitable constructor methods,  accessor method (getDiscount),  mutator method (setDiscount),  overriden toString method, and static announcement method.  It has also its own bill method which computes the bill as a function of the discount and the price.
  • 16. ProgrammingWithJava ICS201The Sale and DiscountSale Classes  The Sale class lessThan method  Note the bill() method invocations: public boolean lessThan (Sale otherSale) { if (otherSale == null) { System.out.println("Error:null object"); System.exit(0); } return (bill( ) < otherSale.bill( )); }
  • 17. ProgrammingWithJava ICS201The Sale and DiscountSale Classes  The Sale class bill() method: public double bill( ) { return price; }  The DiscountSale class bill() method: public double bill( ) { double fraction = discount/100; return (1 - fraction) * getPrice( ); }
  • 18. ProgrammingWithJava ICS201 18 The Sale and DiscountSale Classes  Given the following in a program: . . . Sale simple = new sale(“xx", 10.00); DiscountSale discount = new DiscountSale(“xx", 11.00, 10); . . . if (discount.lessThan(simple)) System.out.println("$" + discount.bill() + " < " + "$" + simple.bill() + " because late-binding works!"); . . .  Output would be: $9.90 < $10 because late-binding works!
  • 19. ProgrammingWithJava ICS201 19 The Sale and DiscountSale Classes  In the previous example, the boolean expression in the if statement returns true.  As the output indicates, when the lessThan method in the Sale class is executed, it knows which bill() method to invoke  The DiscountSale class bill() method for discount, and the Sale class bill() method for simple.  Note that when the Sale class was created and compiled, the DiscountSale class and its bill() method did not yet exist  These results are made possible by late-binding
  • 20. ProgrammingWithJava ICS201 20 The final Modifier  A method marked final indicates that it cannot be overridden with a new definition in a derived class  If final, the compiler can use early binding with the method public final void someMethod() { . . . }  A class marked final indicates that it cannot be used as a base class from which to derive any other classes
  • 21. ProgrammingWithJava ICS201 21 Upcasting and Downcasting  Upcasting is when an object of a derived class is assigned to a variable of a base class (or any ancestor class): Example: class Shape { int xpos, ypos ; public Shape(int x , int y){ xpos = x ; ypos = y ; } public void Draw() { System.out.println("Draw method called of class Shape") ; } }
  • 22. ProgrammingWithJava ICS201 22 Upcasting and Downcasting class Circle extends Shape { int r ; public Circle(int x1 , int y1 , int r1){ super(x1 , y1) ; r = r1 ; } public void Draw() { System.out.println("Draw method called of class Circle") ; } } class UpcastingDemo { public static void main (String [] args) { Shape s = new Circle(10 , 20 , 4) ; s.Draw() ; } } Output: Draw method called of class Circle
  • 23. ProgrammingWithJava ICS201 23 Upcasting and Downcasting  When we wrote Shape S = new Circle(10 , 20 , 4), we have cast Circle to the type Shape.  This is possible because Circle has been derived from Shape  From Circle, we are moving up to the object hierarchy to the type Shape, so we are casting our object “upwards” to its parent type.
  • 24. ProgrammingWithJava ICS201 24 Upcasting and Downcasting  Downcasting is when a type cast is performed from a base class to a derived class (or from any ancestor class to any descendent class). Example: class Shape { int xpos, ypos ; public Shape(int x , int y){ xpos = x ; ypos = y ; } public void Draw() { System.out.println("Draw method called of class Shape") ; } }
  • 25. ProgrammingWithJava ICS201 25 Upcasting and Downcasting class Circle extends Shape { int r ; public Circle(int x1 , int y1 , int r1){ super(x1 , y1) ; r = r1 ; } public void Draw() { System.out.println("Draw method called of class Circle") ; } public void Surface() { System.out.println("The surface of the circle is " + ((Math.PI)*r*r)); } }
  • 26. ProgrammingWithJava ICS201 26 Upcasting and Downcasting class DowncastingDemo { public static void main (String [] args) { Shape s = new Circle(10 , 20 , 4) ; ((Circle) s).Surface() ; } } Output: The surface of the circle is 50.26
  • 27. ProgrammingWithJava ICS201 27 Upcasting and Downcasting  When we wrote Shape s = new Circle(10 , 20 , 4) we have cast Circle to the type shape.  In that case, we are only able to use methods found in Shape, that is, Circle has inherited all the properties and methods of Shape.  If we want to call Surface() method, we need to down- cast our type to Circle. In this case, we will move down the object hierarchy from Shape to Circle :  ((Circle) s).Surface() ;
  • 28. ProgrammingWithJava ICS201 28 Downcasting  It is the responsibility of the programmer to use downcasting only in situations where it makes sense  The compiler does not check to see if downcasting is a reasonable thing to do  Using downcasting in a situation that does not make sense usually results in a run-time error.