SlideShare a Scribd company logo
Polymorphism
Lecture Objectives
• To understand the concept of polymorphism
• To understand the concept of static or early
binding
• To understand the concept of dynamic or late
binding
Polymorphism
• Polymorphism comes from Greek meaning “many
forms.”
• In Java, polymorphism refers to the dynamic binding
mechanism that determines which method definition
will be used when a method name has been
overridden.
• Thus, polymorphism refers to dynamic binding.
Polymorphism (Cont’d)
• Can treat an object of a subclass as an object of
its superclass
 A reference variable of a superclass type can point to an
object of its subclass
Person name, nameRef;
PartTimeEmployee employee, employeeRef;
name = new Person("John", "Blair");
employee = new PartTimeEmployee("Susan", "Johnson",
12.50, 45);
nameRef = employee;
System.out.println("nameRef: " + nameRef);
nameRef: Susan Johnson wages are: $562.5
Polymorphism (Cont’d)
• Late binding or dynamic binding (run-time
binding):
 Method to be executed is determined at execution
time, not compile time
• Polymorphism: to assign multiple meanings
to the same method name
• Implemented using late binding
Polymorphism (Cont’d)
• The reference variable name or nameRef can point
to any object of the class Person or the class
PartTimeEmployee
• These reference variables have many forms, that
is, they are polymorphic reference variables
• They can refer to objects of their own class or to
objects of the classes inherited from their class
Polymorphism (Cont’d)
• Can declare a method of a class final using the
keyword final
• If a method of a class is declared final, it
cannot be overridden with a new definition in a
derived class
public final void doSomeThing(){
//...
}
Polymorphism (Cont’d)
• Can also declare a class final using the keyword
final
• If a class is declared final, then no other class
can be derived from this class
• Java does not use late binding for methods that
are private, marked final, or static
Polymorphism (Cont’d)
• You cannot automatically make reference variable
of subclass type point to object of its superclass
• Suppose that supRef is a reference variable of a
superclass type and supRef points to an object of
its subclass:
 Can use a cast operator on supRef and make a reference
variable of the subclass point to the object
 If supRef does not point to a subclass object and you use a
cast operator on supRef to make a reference variable of the
subclass point to the object, then Java will throw a
ClassCastException—indicating that the class cast is
not allowed
Polymorphism (Cont’d)
• Operator instanceof: determines whether a
reference variable that points to an object is of a
particular class type
• This expression evaluates to true if p points to an
object of the class BoxShape; otherwise it
evaluates to false
p instanceof BoxShape
Polymorphism (Cont’d)
• Interface variable holds reference to object of
a class that implements the interface
Measurable x;
Note that the object to which x refers doesn't
have type Measurable; the type of the object
is some class that implements the
Measurable interface
Continued…
x = new BankAccount(10000);
x = new Coin(0.1, "dime");
Polymorphism (Cont’d)
• You can call any of the interface methods:
• Which method is called?
double m = x.getMeasure();
Polymorphism (Cont’d)
• Depends on the actual object.
• If x refers to a bank account, calls
BankAccount.getMeasure()
• If x refers to a coin, calls Coin.getMeasure()
• Polymorphism (many shapes): Behavior can
vary depending on the actual type of an object
Continued…
Polymorphism (Cont’d)
• Called late binding: resolved at runtime
• Different from overloading; overloading is
resolved by the compiler (early binding)
Dynamic Binding
• Different objects can invoke different method definitions
using the same method name.
• The type of object being referenced at the time of the
method call, not the type of reference that was declared,
determines which method is invoked.
• For example, if the reference b references a Box object and
the reference t references a Triangle object, b and t invoke
different definitions of the method drawAt() even of b and t
are declared to be of type Figure.
Dynamic Binding (Cont’d)
• Consider the following example:
Figure f;
Box b = new Box(1, 4, 4);
f = b;
f.drawAt(2);
Triangle t = new Triangle(1,2);
f = t;
f.drawAt(2);
• The method drawAt() is inherited from class Figure
and is not overridden.
• But, method drawHere() is invoked within the
definition of method drawAt(), and method
drawHere() is overridden.
• The type of object referred to by f determines which
method drawHere() is invoked.
Dynamic Binding (Cont’d)
Type Checking and Dynamic Binding
• Recall that an object reference to an ancestor class can
refer to an object of a descendant class.
• However, you can invoke only a method in class Person
with the variable p.
Employee e = new Employee();
Person p;
p = e;
• However, if a method is overridden in the class
Employee, and variable p references an Employee
object, then the method in class Employee is used.
• The variable determines what methods can be used, but
the type referenced by the object determines which
definition of the method will be used.
Type Checking and Dynamic Binding (Cont’d)
Type Checking and Dynamic Binding (Cont’d)
• To use a method name in the class Employee with
an object named by the variable p of type Person,
use a type cast.
• Example:
Employee e = (Employee)p;
e.setEmployeeNumber(5678);
• However, even a type cast cannot fool Java!
Example:
will use the definition of the method drawHere() given
in class Box, not the definition of drawHere() given
in class Figure.
Type Checking and Dynamic Binding (Cont’d)
Box b = new Box (1, 4, 4);
Figure f = (Figure)b;
f. drawHere()
• You are unlikely to assign an object of a descendant
type to a variable of a parent type, at least not directly.
• But, such an assignment can occur indirectly by
providing an argument of a descendant type for a
method that has a parameter of an ancestor type.
Type Checking and Dynamic Binding (Cont’d)
Dynamic Binding with the toString()
Method
• Recall the method toString() typically is used to prepare
and return a string, describing an object, for output to
the screen.
• The name of this method can be omitted, thanks to
dynamic binding, because one definition of method
println() expects a single argument of type Object which
it uses to invoke the method toString() associated with
the object.
Subtle Difference
• Dynamic binding refers to the process carried out by the
computer.
• Polymorphism can be thought of as something objects
do.
• Polymorphism, encapsulation, and inheritance, and
considered to be the main features of object-oriented
programming.
A Better equals() Method
• Sometimes the method equals() from class Object is
overloaded when it should have been overridden.
 This occurs when its parameter is not of type Object.
• Usually, this is all right.
A Better equals() Method (Cont’d)
• But, if the method equals() is called with an object of
class Object as its argument, the method equals()
from class Object will be invoked.
• The problem is fixed by changing the formal parameter in
the overriding method so that it is a parameter of type
Object.
• However, this allows the argument to be any type of object,
which can produce a run-time error.
• But, we can determine if an object is of the correct type
using:
• Finally, we should return false when comparing an object
to a null reference.
A Better equals() Method (Cont’d)
Object instanceof Class_Name
• The improved equals() method:
A Better equals() Method (Cont’d)
public boolean equals(Object otherObject) {
if(otherObject == null)
return false;
else if(!(otherObject instanceof Student))
return false;
else {
Student otherStudent = (Student) otherObject; // Downcast!!
return (this.studentNumbemer == otherStudent.studentNumber));
}
}
Benefits of Polymorphism
• Polymorphism enables programmers to deal in
generalities and let the execution-time
environment handle the specifics. Programmers
can command objects to behave in manners
appropriate to those objects, without knowing the
types of the objects (as long as the objects belong
to the same inheritance hierarchy).
• Polymorphism promotes extensibility: Software
that invokes polymorphic behavior is
independent of the object types to which
messages are sent. New object types that can
respond to existing method calls can be
incorporated into a system without requiring
modification of the base system. Only client code
that instantiates new objects must be modified to
accommodate new types.
Benefits of Polymorphism (Cont’d)
1 // PolymorphismTest.java
2 // Assigning superclass and subclass references to superclass and
3 // subclass variables.
4
5 public class PolymorphismTest
6 {
7 public static void main( String args[] )
8 {
9 // assign superclass reference to superclass variable
10 CommissionEmployee3 commissionEmployee = new CommissionEmployee3(
11 "Sue", "Jones", "222-22-2222", 10000, .06 );
12
13 // assign subclass reference to subclass variable
14 BasePlusCommissionEmployee4 basePlusCommissionEmployee =
15 new BasePlusCommissionEmployee4(
16 "Bob", "Lewis", "333-33-3333", 5000, .04, 300 );
17
18 // invoke toString on superclass object using superclass variable
19 System.out.printf( "%s %s:nn%snn",
20 "Call CommissionEmployee3's toString with superclass reference ",
21 "to superclass object", commissionEmployee.toString() );
22
23 // invoke toString on subclass object using subclass variable
24 System.out.printf( "%s %s:nn%snn",
25 "Call BasePlusCommissionEmployee4's toString with subclass",
26 "reference to subclass object",
27 basePlusCommissionEmployee.toString() );
28
Typical reference assignments
Testing Polymorphism
29 // invoke toString on subclass object using superclass variable
30 CommissionEmployee3 commissionEmployee2 =
31 basePlusCommissionEmployee;
32 System.out.printf( "%s %s:nn%sn",
33 "Call BasePlusCommissionEmployee4's toString with superclass",
34 "reference to subclass object", commissionEmployee2.toString() );
35 } // end main
36 } // end class PolymorphismTest
Call CommissionEmployee3's toString with superclass reference to superclass
object:
commission employee: Sue Jones
social security number: 222-22-2222
gross sales: 10000.00
commission rate: 0.06
Call BasePlusCommissionEmployee4's toString with subclass reference to
subclass object:
base-salaried commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: 5000.00
commission rate: 0.04
base salary: 300.00
Call BasePlusCommissionEmployee4's toString with superclass reference to
subclass object:
base-salaried commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: 5000.00
commission rate: 0.04
base salary: 300.00
Assign a reference to a
basePlusCommissionEmployee objec
to a CommissionEmployee3 variable
Polymorphically call
basePlusCommissionEmployee’s
toString method
Testing Polymorphism (Cont’d)

More Related Content

What's hot

OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - Polymorphism
Mudasir Qazi
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Elizabeth alexander
 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
Object-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism UnleashedObject-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism Unleashed
Naresh Chintalcheru
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
cprogrammings
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
Java2Blog
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Lovely Professional University
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
rattaj
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Ahmed Za'anin
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Polymorphism
PolymorphismPolymorphism
PolymorphismAmir Ali
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
Home
 
Java Polymorphism
Java PolymorphismJava Polymorphism
Java Polymorphism
Soba Arjun
 
polymorphism
polymorphism polymorphism
polymorphism
Imtiaz Hussain
 
Generics
GenericsGenerics
Generics
adil raja
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Nochiketa Chakraborty
 

What's hot (20)

Polymorphism
PolymorphismPolymorphism
Polymorphism
 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - Polymorphism
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Object-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism UnleashedObject-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism Unleashed
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
 
Java Polymorphism
Java PolymorphismJava Polymorphism
Java Polymorphism
 
polymorphism
polymorphism polymorphism
polymorphism
 
Generics
GenericsGenerics
Generics
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Viewers also liked

Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
M. Raihan
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Sagar Savale
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Duane Wesley
 
Seminar on polymorphism
Seminar on polymorphismSeminar on polymorphism
Seminar on polymorphism023henil
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
Oum Saokosal
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Hitesh Kumar
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 
Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
baabtra.com - No. 1 supplier of quality freshers
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
Anup Burange
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
Abbas Ajmal
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Assignment on errors
Assignment on errorsAssignment on errors

Viewers also liked (19)

Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Seminar on polymorphism
Seminar on polymorphismSeminar on polymorphism
Seminar on polymorphism
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Assignment on errors
Assignment on errorsAssignment on errors
Assignment on errors
 

Similar to JAVA Polymorphism

Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
SURBHI SAROHA
 
Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmell
hyunglak kim
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
riyawagh2
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
Synapseindiappsdevelopment
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
It Academy
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 

Similar to JAVA Polymorphism (20)

Classes2
Classes2Classes2
Classes2
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Chap11
Chap11Chap11
Chap11
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Hemajava
HemajavaHemajava
Hemajava
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
 
Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmell
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 

Recently uploaded

Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 

Recently uploaded (20)

Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 

JAVA Polymorphism

  • 2. Lecture Objectives • To understand the concept of polymorphism • To understand the concept of static or early binding • To understand the concept of dynamic or late binding
  • 3. Polymorphism • Polymorphism comes from Greek meaning “many forms.” • In Java, polymorphism refers to the dynamic binding mechanism that determines which method definition will be used when a method name has been overridden. • Thus, polymorphism refers to dynamic binding.
  • 4. Polymorphism (Cont’d) • Can treat an object of a subclass as an object of its superclass  A reference variable of a superclass type can point to an object of its subclass Person name, nameRef; PartTimeEmployee employee, employeeRef; name = new Person("John", "Blair"); employee = new PartTimeEmployee("Susan", "Johnson", 12.50, 45); nameRef = employee; System.out.println("nameRef: " + nameRef); nameRef: Susan Johnson wages are: $562.5
  • 5. Polymorphism (Cont’d) • Late binding or dynamic binding (run-time binding):  Method to be executed is determined at execution time, not compile time • Polymorphism: to assign multiple meanings to the same method name • Implemented using late binding
  • 6. Polymorphism (Cont’d) • The reference variable name or nameRef can point to any object of the class Person or the class PartTimeEmployee • These reference variables have many forms, that is, they are polymorphic reference variables • They can refer to objects of their own class or to objects of the classes inherited from their class
  • 7. Polymorphism (Cont’d) • Can declare a method of a class final using the keyword final • If a method of a class is declared final, it cannot be overridden with a new definition in a derived class public final void doSomeThing(){ //... }
  • 8. Polymorphism (Cont’d) • Can also declare a class final using the keyword final • If a class is declared final, then no other class can be derived from this class • Java does not use late binding for methods that are private, marked final, or static
  • 9. Polymorphism (Cont’d) • You cannot automatically make reference variable of subclass type point to object of its superclass • Suppose that supRef is a reference variable of a superclass type and supRef points to an object of its subclass:  Can use a cast operator on supRef and make a reference variable of the subclass point to the object  If supRef does not point to a subclass object and you use a cast operator on supRef to make a reference variable of the subclass point to the object, then Java will throw a ClassCastException—indicating that the class cast is not allowed
  • 10. Polymorphism (Cont’d) • Operator instanceof: determines whether a reference variable that points to an object is of a particular class type • This expression evaluates to true if p points to an object of the class BoxShape; otherwise it evaluates to false p instanceof BoxShape
  • 11. Polymorphism (Cont’d) • Interface variable holds reference to object of a class that implements the interface Measurable x; Note that the object to which x refers doesn't have type Measurable; the type of the object is some class that implements the Measurable interface Continued… x = new BankAccount(10000); x = new Coin(0.1, "dime");
  • 12. Polymorphism (Cont’d) • You can call any of the interface methods: • Which method is called? double m = x.getMeasure();
  • 13. Polymorphism (Cont’d) • Depends on the actual object. • If x refers to a bank account, calls BankAccount.getMeasure() • If x refers to a coin, calls Coin.getMeasure() • Polymorphism (many shapes): Behavior can vary depending on the actual type of an object Continued…
  • 14. Polymorphism (Cont’d) • Called late binding: resolved at runtime • Different from overloading; overloading is resolved by the compiler (early binding)
  • 15. Dynamic Binding • Different objects can invoke different method definitions using the same method name. • The type of object being referenced at the time of the method call, not the type of reference that was declared, determines which method is invoked. • For example, if the reference b references a Box object and the reference t references a Triangle object, b and t invoke different definitions of the method drawAt() even of b and t are declared to be of type Figure.
  • 16. Dynamic Binding (Cont’d) • Consider the following example: Figure f; Box b = new Box(1, 4, 4); f = b; f.drawAt(2); Triangle t = new Triangle(1,2); f = t; f.drawAt(2);
  • 17. • The method drawAt() is inherited from class Figure and is not overridden. • But, method drawHere() is invoked within the definition of method drawAt(), and method drawHere() is overridden. • The type of object referred to by f determines which method drawHere() is invoked. Dynamic Binding (Cont’d)
  • 18. Type Checking and Dynamic Binding • Recall that an object reference to an ancestor class can refer to an object of a descendant class. • However, you can invoke only a method in class Person with the variable p. Employee e = new Employee(); Person p; p = e;
  • 19. • However, if a method is overridden in the class Employee, and variable p references an Employee object, then the method in class Employee is used. • The variable determines what methods can be used, but the type referenced by the object determines which definition of the method will be used. Type Checking and Dynamic Binding (Cont’d)
  • 20. Type Checking and Dynamic Binding (Cont’d) • To use a method name in the class Employee with an object named by the variable p of type Person, use a type cast. • Example: Employee e = (Employee)p; e.setEmployeeNumber(5678);
  • 21. • However, even a type cast cannot fool Java! Example: will use the definition of the method drawHere() given in class Box, not the definition of drawHere() given in class Figure. Type Checking and Dynamic Binding (Cont’d) Box b = new Box (1, 4, 4); Figure f = (Figure)b; f. drawHere()
  • 22. • You are unlikely to assign an object of a descendant type to a variable of a parent type, at least not directly. • But, such an assignment can occur indirectly by providing an argument of a descendant type for a method that has a parameter of an ancestor type. Type Checking and Dynamic Binding (Cont’d)
  • 23. Dynamic Binding with the toString() Method • Recall the method toString() typically is used to prepare and return a string, describing an object, for output to the screen. • The name of this method can be omitted, thanks to dynamic binding, because one definition of method println() expects a single argument of type Object which it uses to invoke the method toString() associated with the object.
  • 24. Subtle Difference • Dynamic binding refers to the process carried out by the computer. • Polymorphism can be thought of as something objects do. • Polymorphism, encapsulation, and inheritance, and considered to be the main features of object-oriented programming.
  • 25. A Better equals() Method • Sometimes the method equals() from class Object is overloaded when it should have been overridden.  This occurs when its parameter is not of type Object. • Usually, this is all right.
  • 26. A Better equals() Method (Cont’d) • But, if the method equals() is called with an object of class Object as its argument, the method equals() from class Object will be invoked. • The problem is fixed by changing the formal parameter in the overriding method so that it is a parameter of type Object.
  • 27. • However, this allows the argument to be any type of object, which can produce a run-time error. • But, we can determine if an object is of the correct type using: • Finally, we should return false when comparing an object to a null reference. A Better equals() Method (Cont’d) Object instanceof Class_Name
  • 28. • The improved equals() method: A Better equals() Method (Cont’d) public boolean equals(Object otherObject) { if(otherObject == null) return false; else if(!(otherObject instanceof Student)) return false; else { Student otherStudent = (Student) otherObject; // Downcast!! return (this.studentNumbemer == otherStudent.studentNumber)); } }
  • 29. Benefits of Polymorphism • Polymorphism enables programmers to deal in generalities and let the execution-time environment handle the specifics. Programmers can command objects to behave in manners appropriate to those objects, without knowing the types of the objects (as long as the objects belong to the same inheritance hierarchy).
  • 30. • Polymorphism promotes extensibility: Software that invokes polymorphic behavior is independent of the object types to which messages are sent. New object types that can respond to existing method calls can be incorporated into a system without requiring modification of the base system. Only client code that instantiates new objects must be modified to accommodate new types. Benefits of Polymorphism (Cont’d)
  • 31. 1 // PolymorphismTest.java 2 // Assigning superclass and subclass references to superclass and 3 // subclass variables. 4 5 public class PolymorphismTest 6 { 7 public static void main( String args[] ) 8 { 9 // assign superclass reference to superclass variable 10 CommissionEmployee3 commissionEmployee = new CommissionEmployee3( 11 "Sue", "Jones", "222-22-2222", 10000, .06 ); 12 13 // assign subclass reference to subclass variable 14 BasePlusCommissionEmployee4 basePlusCommissionEmployee = 15 new BasePlusCommissionEmployee4( 16 "Bob", "Lewis", "333-33-3333", 5000, .04, 300 ); 17 18 // invoke toString on superclass object using superclass variable 19 System.out.printf( "%s %s:nn%snn", 20 "Call CommissionEmployee3's toString with superclass reference ", 21 "to superclass object", commissionEmployee.toString() ); 22 23 // invoke toString on subclass object using subclass variable 24 System.out.printf( "%s %s:nn%snn", 25 "Call BasePlusCommissionEmployee4's toString with subclass", 26 "reference to subclass object", 27 basePlusCommissionEmployee.toString() ); 28 Typical reference assignments Testing Polymorphism
  • 32. 29 // invoke toString on subclass object using superclass variable 30 CommissionEmployee3 commissionEmployee2 = 31 basePlusCommissionEmployee; 32 System.out.printf( "%s %s:nn%sn", 33 "Call BasePlusCommissionEmployee4's toString with superclass", 34 "reference to subclass object", commissionEmployee2.toString() ); 35 } // end main 36 } // end class PolymorphismTest Call CommissionEmployee3's toString with superclass reference to superclass object: commission employee: Sue Jones social security number: 222-22-2222 gross sales: 10000.00 commission rate: 0.06 Call BasePlusCommissionEmployee4's toString with subclass reference to subclass object: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00 Call BasePlusCommissionEmployee4's toString with superclass reference to subclass object: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00 Assign a reference to a basePlusCommissionEmployee objec to a CommissionEmployee3 variable Polymorphically call basePlusCommissionEmployee’s toString method Testing Polymorphism (Cont’d)