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

PPT
Class & Object - User Defined Method
PPT
Basic c#
PPTX
Chapter 6.6
PPT
3433 Ch10 Ppt
PPTX
14. Java defining classes
ZIP
147301 nol
PPTX
20.4 Java interfaces and abstraction
Class & Object - User Defined Method
Basic c#
Chapter 6.6
3433 Ch10 Ppt
14. Java defining classes
147301 nol
20.4 Java interfaces and abstraction

What's hot (16)

PDF
PDF
Lec 7 28_aug [compatibility mode]
PPTX
20.3 Java encapsulation
PPTX
OOP with Java - continued
PPTX
11. Objects and Classes
PDF
Object oriented programming
PPTX
14 Defining Classes
PPTX
20.1 Java working with abstraction
PPTX
20.2 Java inheritance
PDF
The Ring programming language version 1.3 book - Part 24 of 88
PPT
KEY
Simple Scala DSLs
PDF
The Ring programming language version 1.5 book - Part 6 of 31
PPT
Implementation of interface9 cm604.30
PPT
PDF
Lec 8 03_sept [compatibility mode]
Lec 7 28_aug [compatibility mode]
20.3 Java encapsulation
OOP with Java - continued
11. Objects and Classes
Object oriented programming
14 Defining Classes
20.1 Java working with abstraction
20.2 Java inheritance
The Ring programming language version 1.3 book - Part 24 of 88
Simple Scala DSLs
The Ring programming language version 1.5 book - Part 6 of 31
Implementation of interface9 cm604.30
Lec 8 03_sept [compatibility mode]
Ad

Viewers also liked (19)

PPT
Abstract class
PDF
Chap 4 Review.pdf
PDF
3-1 to 3-3 Review Day.pdf
PPTX
Extending burp with python
PPTX
Naïve bayes
PDF
Function operations and compositions
PDF
Lab 1
PPTX
Decision tree
PDF
Res epre61 13
PPT
Object Oriented Analysis &amp; Design
PPT
Ooad overview
PPTX
Test driven development
PPT
Hash mac algorithms
PPTX
Cobol, lisp, and python
PPTX
Decision tree
PPTX
Crypto passport authentication
PPT
Basic dns-mod
PPT
Data preprocessing
PPTX
Google appenginejava.ppt
Abstract class
Chap 4 Review.pdf
3-1 to 3-3 Review Day.pdf
Extending burp with python
Naïve bayes
Function operations and compositions
Lab 1
Decision tree
Res epre61 13
Object Oriented Analysis &amp; Design
Ooad overview
Test driven development
Hash mac algorithms
Cobol, lisp, and python
Decision tree
Crypto passport authentication
Basic dns-mod
Data preprocessing
Google appenginejava.ppt
Ad

Similar to Polymorphism (20)

PDF
Refactoring Chapter11
PPT
basic concepts
PDF
Lec 9 05_sept [compatibility mode]
PPT
Chap08
PPTX
Intro to object oriented programming
PPT
Visula C# Programming Lecture 6
PPTX
Lab4-Software-Construction-BSSE5.pptx ppt
PDF
Object-oriented Basics
PPTX
Java interface
PDF
Object Oriented Solved Practice Programs C++ Exams
PPTX
Ch2 Elementry Programmin as per gtu oop.pptx
DOCX
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
PPTX
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
PPTX
Computer programming 2 Lesson 15
PPTX
‫Chapter3 inheritance
PPT
9781439035665 ppt ch08
DOCX
Diifeerences In C#
PPT
Inheritance and-polymorphism
DOCX
Uta005
PPT
Object and class
Refactoring Chapter11
basic concepts
Lec 9 05_sept [compatibility mode]
Chap08
Intro to object oriented programming
Visula C# Programming Lecture 6
Lab4-Software-Construction-BSSE5.pptx ppt
Object-oriented Basics
Java interface
Object Oriented Solved Practice Programs C++ Exams
Ch2 Elementry Programmin as per gtu oop.pptx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
Computer programming 2 Lesson 15
‫Chapter3 inheritance
9781439035665 ppt ch08
Diifeerences In C#
Inheritance and-polymorphism
Uta005
Object and class

More from James Wong (20)

PPT
Data race
PPT
Multi threaded rtos
PPT
Recursion
PPTX
Business analytics and data mining
PPTX
Data mining and knowledge discovery
PPTX
Cache recap
PPTX
Big picture of data mining
PPTX
How analysis services caching works
PPTX
Optimizing shared caches in chip multiprocessors
PPTX
Directory based cache coherence
PPT
Abstract data types
PPTX
Abstraction file
PPTX
Hardware managed cache
PPTX
Object model
PPTX
Object oriented analysis
PPTX
Concurrency with java
PPTX
Data structures and algorithms
PPTX
Cobol, lisp, and python
PPTX
Inheritance
PPTX
Api crash
Data race
Multi threaded rtos
Recursion
Business analytics and data mining
Data mining and knowledge discovery
Cache recap
Big picture of data mining
How analysis services caching works
Optimizing shared caches in chip multiprocessors
Directory based cache coherence
Abstract data types
Abstraction file
Hardware managed cache
Object model
Object oriented analysis
Concurrency with java
Data structures and algorithms
Cobol, lisp, and python
Inheritance
Api crash

Recently uploaded (20)

PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Hybrid model detection and classification of lung cancer
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Encapsulation theory and applications.pdf
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
August Patch Tuesday
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
project resource management chapter-09.pdf
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Hybrid model detection and classification of lung cancer
Group 1 Presentation -Planning and Decision Making .pptx
Assigned Numbers - 2025 - Bluetooth® Document
Encapsulation theory and applications.pdf
TLE Review Electricity (Electricity).pptx
Accuracy of neural networks in brain wave diagnosis of schizophrenia
MIND Revenue Release Quarter 2 2025 Press Release
August Patch Tuesday
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
project resource management chapter-09.pdf
Enhancing emotion recognition model for a student engagement use case through...
A novel scalable deep ensemble learning framework for big data classification...
Building Integrated photovoltaic BIPV_UPV.pdf
DP Operators-handbook-extract for the Mautical Institute
SOPHOS-XG Firewall Administrator PPT.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

Polymorphism

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