0% found this document useful (0 votes)
132 views27 pages

Polymorphism: Object Oriented Programming

This document discusses polymorphism and binding in object-oriented programming. It defines polymorphism as the ability for a method call to behave differently depending on the type of object it references. Binding is the process of associating a method definition with a method invocation. Early or static binding occurs at compile time, while late or dynamic binding occurs at runtime. Runtime polymorphism is achieved through method overriding in subclasses.

Uploaded by

Rehman Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views27 pages

Polymorphism: Object Oriented Programming

This document discusses polymorphism and binding in object-oriented programming. It defines polymorphism as the ability for a method call to behave differently depending on the type of object it references. Binding is the process of associating a method definition with a method invocation. Early or static binding occurs at compile time, while late or dynamic binding occurs at runtime. Runtime polymorphism is achieved through method overriding in subclasses.

Uploaded by

Rehman Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Polymorphism

Lecture 11
Object Oriented Programming
Programming Concept – Binding
• The process of associating a method definition with a
method invocation is called binding

• If the method definition is associated with its invocation


when the code is compiled, that is called early binding
or static binding

• If the method definition is associated with its invocation


when the method is invoked (at run time), that is called
late binding or dynamic binding
Binding
Programming Concept – Binding
stop() is a static method and hence
cannot be overridden. So binding of the
stop() method happens at the compile
Early & Late Binding

time itself (early binding). On the other


hand, start() is a non-static method
overridden in the child class. So, the
information about the type of object is
available at the run time only (late
binding), and hence the start() method
of the Car class is called.
Introduction to Polymorphism
• 3 main programming mechanisms constitute OOP
‒ Encapsulation
‒ Inheritance
‒ 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
Polymorphism
• The term polymorphism literally means "having many forms"
• Single method call behaves differently depending on the type
of the object which the call references
• Polymorphism means
‒ When a program invokes a method through a superclass variable,
the correct subclass version of the method is called, based on the
type of the reference stored in the superclass variable
‒ The same method name and signature can cause different actions to
occur, depending on the type of object on which the method is
invoked
‒ Facilitates adding new classes to a system with minimal
modifications to the system’s code
Real Life Example
• Cat makes sound meow.
‒ Let's call this action makeSound() because remember,
a method can represent an action.
• Dog makes sound woof.
‒ We can also call this action makeSound().
• Let's also just pretend that all animals can makeSound().

• Thus, makeSound(), depending on the type of animal, does


something different. The action acts differently based on the
object.
• This is polymorphism
Types of Polymorphisms
• There are 2 types of polymorphisms in Java:
‒ Compile time polymorphism
‒ Runtime polymorphism

• We can perform polymorphism in java by


‒ method overloading (compile time)
(If a class has multiple methods having same name but
different in parameters, it is known as Method Overloading. )
‒ method overriding (runtime)
Compile time Polymorphism
(Static Binding or method overloading)
• This is used to write the program in such a way, that
flow of control is decided in compile time itself
• It is achieved using method overloading
• In method overloading, an object can have two or more
methods with same name, BUT, with their method
parameters different.
• These parameters may be different based on their type
or count
class Overload {
void demo (int a) {
Compile time Polymorphism
System.out.println ("a: " + a);
}
Overloaded
void demo (int a, int b) {
Method
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading {
public static void main (String args []) {
Overload Obj = new Overload();
double result;
Obj.demo(10);
Example

Obj.demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Run-time Polymorphism
• Runtime polymorphism or Dynamic Method Dispatch
is a process in which a call to an overridden method
is resolved at runtime rather than compile-time
Holiday
• The compiler only checks the compile time error and
does not bind the method call with any actual
method
Christmas
• This method binding if is done at runtime by runtime
environment then we say dynamic polymorphism is
being implemented in the program Holiday day;
day = new
• An object reference can refer to an object of its
Christmas();
class, or to an object of any class related to it by
inheritance
• For example, if the Holiday class is used to derive a
class called Christmas, then a Holiday reference
could be used to point to a Christmas object
• Lets suppose we have a class Animal

public class Animal{


makesound(){}
}
Run-time Polymorphism

• Lets suppose Dog extends Animal such that

public class Dog extends Animal{


makesound(){
return “woof”;
}
}

• To instantiate an Object of Dog, normally you will see this:-


Example
• However, you can also declare a variable by its supertype or abstract
type to make it more generic. we can also do this:-

“dog” has reference type “Animal”


but true type “Dog”
Run-time Polymorphism

• we just made a Dog but declared it as an Animal!

• So, which version of makeSound() would you use if you saw Animal
animal = new Dog() ?

• Would you choose the Animal's version or the Dog's version?


Example

• The answer is that Java will choose the true type, and the true type is the
object that actually gets created
• In this example, what we are really creating is a Dog, even though we are
referencing the variable as an Animal
Dynamic Binding
Why use Polymorphism?
• Why in the world wouldn't we just do Dog dog = new Dog() ?
• The answer is that by using abstraction, you can actually group
many different types of objects together
• Let's see how we can use this concept for storing objects:

• We could not do the above if the Cat objects and Dog objects were
made the traditional way and not by referencing them as Animals
Run-time Polymorphism
• In Java, a variable declared type of class A can hold a
reference to an object of class A or an object belonging
to any subclasses of class A.
• Program is able to resolve the correct method related to
the subclass object at runtime. -runtime polymorphism
• Provides the ability to override functionality already
available in the class hierarchy tree.
• At runtime, which version of the method will be invoked
is based on the type of actual object stored in that
reference variable and not on the type of the reference
variable
Run-time Polymorphism
Example
UpCasting & DownCasting
• UpCasting
‒ Assigning a child object to a parent reference
‒ Considered to be a widening conversion or Upcasting
‒ Can be performed by simple assignment

• DownCasting
‒ Assigning a parent object to a child reference
‒ Considered a narrowing conversion or Downcasting
‒ Must be done with a cast
UpCasting
• Upcasting is when an object of a derived class is
assigned to a variable of a base class (or any ancestor
class)

• For Example:
‒ Suppose we defined a class “Base” and one another class with
name “Child”.
‒ We will create the object of child class but we will use the
reference variable of parent class to store the reference of
Child’s object.
Base b = new Child();  //upCasting
Polymorphism via Inheritance
• It is the type of the object being referenced, not the
reference type, that determines which method is invoked

• Suppose the Holiday class has a method called celebrate,


and the Christmas class overrides it
• Now consider the following invocation:
day.celebrate();
‒ If day refers to a Holiday object, it invokes the Holiday version
of celebrate;
‒ if it refers to a Christmas object, it invokes the Christmas
version
Java Runtime Polymorphism

• In this example, we are creating two classes Bike and Splendar.


Splendar class extends Bike class and overrides its run() method.
• We are calling the run method by the reference variable of Parent
Example

class.
• Since it refers to the subclass object and subclass method overrides
the Parent class method, subclass method is invoked at runtime.
Rule: Runtime
Java Runtime Polymorphism
polymorphism
can't be achieved
by data members
Example - data member

• Method is overridden not the data members, so runtime polymorphism


can't be achieved by data members.

• Since we are accessing the data member which is not overridden, hence it
will access the data member of Parent class always.
Java Runtime Polymorphism
Example – Multi-level Inheritance
DownCasting
• UpCasting is when an object of a derived class is assigned to a
variable of a base class (or any ancestor class)
Vehicle v1 = new Vehicle(); //Base class object
Bus b1 = new Bus(2, 55000, 37); //Derived class object
v1 = b1;

• 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)
‒ Downcasting has to be done very carefully. In many cases it doesn't make
sense, or is illegal:
B1 = v1; //will produce compiler error (typemismatch error)
B1 = (Bus)v1; //will produce run-time error (v1 is not instanceof Bus)
Vehicle v2 = new Bus();
Bus b2 = (Bus)v2; //Will not give any error as v2 is instanceof Bus
DownCasting
Example
Uses 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

You might also like