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

Recommendation lektier online %28eng%29
Recommendation lektier online %28eng%29Recommendation lektier online %28eng%29
Recommendation lektier online %28eng%29Elena Zavrotschi
 
LeadershipThroughTeamBuillding
LeadershipThroughTeamBuilldingLeadershipThroughTeamBuillding
LeadershipThroughTeamBuilldingJen K
 
Letter of recommendation
Letter of recommendationLetter of recommendation
Letter of recommendationAreeba Tanveer
 
Torque final
Torque finalTorque final
Torque finalkgnmatin
 
Sql database object
Sql database objectSql database object
Sql database objectFraboni Ec
 
Creating organisation of the future
Creating organisation of the futureCreating organisation of the future
Creating organisation of the futureOPUS Management
 
Business Proposal; Budget Plan for Dairy farm
Business Proposal; Budget Plan for Dairy farmBusiness Proposal; Budget Plan for Dairy farm
Business Proposal; Budget Plan for Dairy farmKanika Verma
 
Báo cáo quyết toán hàng gia công theo thông tư 38
Báo cáo quyết toán hàng gia công theo thông tư 38Báo cáo quyết toán hàng gia công theo thông tư 38
Báo cáo quyết toán hàng gia công theo thông tư 38Doan Tran Ngocvu
 
Digital electronics lab
Digital electronics labDigital electronics lab
Digital electronics labswatymanoja
 
Cafeteria presentation
Cafeteria presentationCafeteria presentation
Cafeteria presentationBlake_Honaker
 

Viewers also liked (18)

Abelaazul
AbelaazulAbelaazul
Abelaazul
 
Recommendation lektier online %28eng%29
Recommendation lektier online %28eng%29Recommendation lektier online %28eng%29
Recommendation lektier online %28eng%29
 
LeadershipThroughTeamBuillding
LeadershipThroughTeamBuilldingLeadershipThroughTeamBuillding
LeadershipThroughTeamBuillding
 
Letter of recommendation
Letter of recommendationLetter of recommendation
Letter of recommendation
 
Recommendation
RecommendationRecommendation
Recommendation
 
Torque final
Torque finalTorque final
Torque final
 
Java
JavaJava
Java
 
Sql database object
Sql database objectSql database object
Sql database object
 
Creating organisation of the future
Creating organisation of the futureCreating organisation of the future
Creating organisation of the future
 
Recommendation_Letter_for_Rudynah_E._Capone[1]
Recommendation_Letter_for_Rudynah_E._Capone[1]Recommendation_Letter_for_Rudynah_E._Capone[1]
Recommendation_Letter_for_Rudynah_E._Capone[1]
 
Recommendation
RecommendationRecommendation
Recommendation
 
Edition#1
Edition#1Edition#1
Edition#1
 
Fiesta de fin de año en el ecuador
Fiesta de fin de año en el ecuadorFiesta de fin de año en el ecuador
Fiesta de fin de año en el ecuador
 
Business Proposal; Budget Plan for Dairy farm
Business Proposal; Budget Plan for Dairy farmBusiness Proposal; Budget Plan for Dairy farm
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
Báo cáo quyết toán hàng gia công theo thông tư 38Báo cáo quyết toán hàng gia công theo thông tư 38
Báo cáo quyết toán hàng gia công theo thông tư 38
 
Digital electronics lab
Digital electronics labDigital electronics lab
Digital electronics lab
 
Cafeteria presentation
Cafeteria presentationCafeteria presentation
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
Tài liệu hướng dẫn báo cáo quyết toán hàng GC và SXXK trên ECUS5 VNACCSTài liệu hướng dẫn báo cáo quyết toán hàng GC và SXXK trên ECUS5 VNACCS
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
 

Similar to Polymorphism

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 Polymorphism (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 Tony Nguyen

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisTony Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceTony Nguyen
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningTony Nguyen
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningTony Nguyen
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryTony Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksTony Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheTony Nguyen
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesTony Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsTony Nguyen
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsTony Nguyen
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaTony Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonTony Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonTony Nguyen
 

More from Tony Nguyen (20)

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
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
 
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
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Inheritance
InheritanceInheritance
Inheritance
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Api crash
Api crashApi crash
Api crash
 

Recently uploaded

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

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.