SlideShare une entreprise Scribd logo
1  sur  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.

Contenu connexe

Tendances

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
 

Tendances (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]
 

En vedette

Abstract class
Abstract classAbstract class
Abstract classJames Wong
 
Chap 4 Review.pdf
Chap 4 Review.pdfChap 4 Review.pdf
Chap 4 Review.pdfbwlomas
 
3-1 to 3-3 Review Day.pdf
3-1 to 3-3 Review Day.pdf3-1 to 3-3 Review Day.pdf
3-1 to 3-3 Review Day.pdfbwlomas
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonJames Wong
 
Function operations and compositions
Function operations and compositionsFunction operations and compositions
Function operations and compositionsbwlomas
 
Res epre61 13
Res epre61 13Res epre61 13
Res epre61 13EPRE
 
Object Oriented Analysis &amp; Design
Object Oriented Analysis &amp; DesignObject Oriented Analysis &amp; Design
Object Oriented Analysis &amp; Designkpthakershy
 
Test driven development
Test driven developmentTest driven development
Test driven developmentYoung Alista
 
Hash mac algorithms
Hash mac algorithmsHash mac algorithms
Hash mac algorithmsYoung Alista
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonYoung Alista
 
Crypto passport authentication
Crypto passport authenticationCrypto passport authentication
Crypto passport authenticationYoung Alista
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessingYoung Alista
 
Google appenginejava.ppt
Google appenginejava.pptGoogle appenginejava.ppt
Google appenginejava.pptYoung Alista
 

En vedette (19)

Abstract class
Abstract classAbstract class
Abstract class
 
Chap 4 Review.pdf
Chap 4 Review.pdfChap 4 Review.pdf
Chap 4 Review.pdf
 
3-1 to 3-3 Review Day.pdf
3-1 to 3-3 Review Day.pdf3-1 to 3-3 Review Day.pdf
3-1 to 3-3 Review Day.pdf
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Naïve bayes
Naïve bayesNaïve bayes
Naïve bayes
 
Function operations and compositions
Function operations and compositionsFunction operations and compositions
Function operations and compositions
 
Lab 1
Lab 1Lab 1
Lab 1
 
Decision tree
Decision treeDecision tree
Decision tree
 
Res epre61 13
Res epre61 13Res epre61 13
Res epre61 13
 
Object Oriented Analysis &amp; Design
Object Oriented Analysis &amp; DesignObject Oriented Analysis &amp; Design
Object Oriented Analysis &amp; Design
 
Ooad overview
Ooad overviewOoad overview
Ooad overview
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Hash mac algorithms
Hash mac algorithmsHash mac algorithms
Hash mac algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Decision tree
Decision treeDecision tree
Decision tree
 
Crypto passport authentication
Crypto passport authenticationCrypto passport authentication
Crypto passport authentication
 
Basic dns-mod
Basic dns-modBasic dns-mod
Basic dns-mod
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 
Google appenginejava.ppt
Google appenginejava.pptGoogle appenginejava.ppt
Google appenginejava.ppt
 

Similaire à 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
 

Similaire à 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
 

Plus de James Wong

Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtosJames Wong
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningJames Wong
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryJames Wong
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningJames Wong
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksJames Wong
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsJames Wong
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceJames Wong
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesJames Wong
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileJames Wong
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheJames Wong
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisJames Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJames Wong
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonJames Wong
 

Plus de James Wong (20)

Data race
Data raceData race
Data race
 
Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtos
 
Recursion
RecursionRecursion
Recursion
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and 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
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Object model
Object modelObject model
Object model
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
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
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Inheritance
InheritanceInheritance
Inheritance
 
Api crash
Api crashApi crash
Api crash
 

Dernier

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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Dernier (20)

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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

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.