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 (18)

PPS
Abelaazul
DOC
Recommendation lektier online %28eng%29
PDF
LeadershipThroughTeamBuillding
DOCX
Letter of recommendation
PDF
Recommendation
PPSX
Torque final
PPTX
PPT
Sql database object
PDF
Creating organisation of the future
PDF
Recommendation_Letter_for_Rudynah_E._Capone[1]
DOCX
Recommendation
PDF
Edition#1
PPT
Fiesta de fin de año en el ecuador
DOCX
Business Proposal; Budget Plan for Dairy farm
PDF
Báo cáo quyết toán hàng gia công theo thông tư 38
DOC
Digital electronics lab
PDF
Cafeteria presentation
PPTX
Tài liệu hướng dẫn báo cáo quyết toán hàng GC và SXXK trên ECUS5 VNACCS
Abelaazul
Recommendation lektier online %28eng%29
LeadershipThroughTeamBuillding
Letter of recommendation
Recommendation
Torque final
Sql database object
Creating organisation of the future
Recommendation_Letter_for_Rudynah_E._Capone[1]
Recommendation
Edition#1
Fiesta de fin de año en el ecuador
Business Proposal; Budget Plan for Dairy farm
Báo cáo quyết toán hàng gia công theo thông tư 38
Digital electronics lab
Cafeteria presentation
Tài liệu hướng dẫn báo cáo quyết toán hàng GC và SXXK trên ECUS5 VNACCS
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 Tony Nguyen (20)

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

Recently uploaded (20)

PDF
A proposed approach for plagiarism detection in Myanmar Unicode text
PPTX
Benefits of Physical activity for teenagers.pptx
PPTX
Microsoft Excel 365/2024 Beginner's training
PPT
Module 1.ppt Iot fundamentals and Architecture
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
Five Habits of High-Impact Board Members
PDF
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
PPT
Geologic Time for studying geology for geologist
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PDF
Credit Without Borders: AI and Financial Inclusion in Bangladesh
DOCX
search engine optimization ppt fir known well about this
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
Zenith AI: Advanced Artificial Intelligence
A proposed approach for plagiarism detection in Myanmar Unicode text
Benefits of Physical activity for teenagers.pptx
Microsoft Excel 365/2024 Beginner's training
Module 1.ppt Iot fundamentals and Architecture
Custom Battery Pack Design Considerations for Performance and Safety
Developing a website for English-speaking practice to English as a foreign la...
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide
Consumable AI The What, Why & How for Small Teams.pdf
The influence of sentiment analysis in enhancing early warning system model f...
Five Habits of High-Impact Board Members
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
Geologic Time for studying geology for geologist
A review of recent deep learning applications in wood surface defect identifi...
NewMind AI Weekly Chronicles – August ’25 Week III
Improvisation in detection of pomegranate leaf disease using transfer learni...
Credit Without Borders: AI and Financial Inclusion in Bangladesh
search engine optimization ppt fir known well about this
Getting started with AI Agents and Multi-Agent Systems
Taming the Chaos: How to Turn Unstructured Data into Decisions
Zenith AI: Advanced Artificial Intelligence

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.