You are on page 1of 38

Object Oriented Programming

Chapter - 4 : Polymorphism

Compiled By Yohans Samuel(MSc)

1
Contents

POLYMORPHISM

1. Polymorphism
2. Runtime Polymorphism
3. Overloading
4. Overriding
5. Casting

2
Polymorphism (1)
• Is a concept by which we can perform a single action in different
ways.
• Polymorphism is derived from 2 greek words: poly and morphs.
• The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
• There are two types of polymorphism in java: compile-time
polymorphism and runtime polymorphism.
• We can perform polymorphism in java by method overloading and
method overriding.
• If you overload methods in java, it is the example of compile time
polymorphism

3
Polymorphism (2)
• Polymorphism is one of the principles in Object Oriented
Programming paradigm.
• The term polymorphism means “a method the same as another in
spelling but with different behavior.”
• Polymorphism is the ability of objects to act depending on the run
time type.
• Polymorphism allows programmers to send the same message to
objects from different classes. i.e., in its simplest from, polymorphism
allows a single variable to refer to objects from different classes.
• Polymorphism enables us to “program in the general” rather than
“program in the specific”.

4
Polymorphism (3)
• In general, connecting a method call to a method body is called
binding.
• When binding is performed before the program is run, it’s called
early binding also called static binding OR compile-time binding.
• When the binding occurs at run-time based on the type of object,
it’s called late binding also called dynamic binding OR run-time
binding.
• When late binding is implemented, there must be some
mechanism to determine the type of the object at run-time and to
call the appropriate method.
• That is, the compiler still doesn’t know the object type, but the
method-call mechanism finds out and calls the correct method
body.
5
Polymorphism (4)
• Method Overloading (Early/Static Binding): Methods with
same name, but the compiler uses three mechanisms to
differentiate the overloaded methods
– Number of parameters
– Data-type of parameters
– Order of parameters

6
Polymorphism (5)
• Method Overriding (Late/Dynamic Binding) : Methods with same
name and signature and applied on inheritance concepts.
• Methods of a subclass override the methods of a super class in a given
inheritance hierarchy.
• Methods of a subclass implement the abstract methods of an abstract
class.
• Methods of a concrete class implement the methods of an interface.

7
Polymorphism (6)

Student
Person
Employee

Rectangle
Shape Triangle

Circle
8
Polymorphism (7)
class Polygon {
class Main {
// method to render a shape
public static void main(String[] args) {
public void render() {
System.out.println("Rendering Polygon...");
} // create an object of Square
} Square s1 = new Square();
class Square extends Polygon { s1.render();
// renders Square
public void render() {
// create an object of Circle
System.out.println("Rendering Square...");
Circle c1 = new Circle();
}
}
c1.render();
class Circle extends Polygon { }
}
// renders circle
public void render() {
System.out.println("Rendering Circle...");
}
}

9
Polymorphism (8)
• In the above example, we have created a superclass: Polygon and
two subclasses: Square and Circle.
• Notice the use of the render() method.
• The main purpose of the render() method is to render the shape.
• However, the process of rendering a square is different than the
process of rendering a circle.
• Hence, the render() method behaves differently in different
classes. Or, we can say render() is polymorphic.

10
Runtime Polymorphism (9)
Why Polymorphism?
• Polymorphism allows us to create consistent code.
• In the previous example, we can also create different methods:
renderSquare() and renderCircle() to render Square and Circle,
respectively.
• This will work perfectly. However, for every shape,
– we need to create different methods.
– It will make our code inconsistent.
• To solve this, polymorphism in Java allows us to create a single
method render() that will behave differently for different shapes.
• Note: The print() method is also an example of polymorphism.
• It is used to print values of different types like char, int, string, etc.

11
Runtime Polymorphism (1)
• 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.
• An overridden method is called through the reference variable
of a superclass.
• The determination of the method to be called is based on the
object being referred to by the reference variable.

12
Runtime Polymorphism (2)
• When reference variable of Parent class refers to the object of
Child class, it is known as upcasting.

class A{}
class B extends A{}
A a=new B();//upcasting

13
Runtime Polymorphism (3)
class Bike{
void run(){ System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");
}
public static void main(String args[]){
Bike b = new Splender();//upcasting
b.run();
}
}
Output: running safely with 60km

14
Runtime Polymorphism (4)
Method is overridden, not the data members, so runtime
polymorphism can’t be achieved by data members.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);
}
Output: 90
15
Runtime Polymorphism (5)
class Animal{ public static void main(String args[]){
void eat(){
Animal a1,a2,a3;
System.out.println("eating");
a1=new Animal();
}
a2=new Dog();
}
class Dog extends Animal{ a3=new BabyDog();
void eat(){ a1.eat();
System.out.println("eating meat"); a2.eat();
} a3.eat();
} }
class BabyDog extends Dog{ }
void eat(){ Output: eating
System.out.println("drinking milk"); eating meat
}
drinking milk
16
Runtime Polymorphism (6)
// Dynamic Method Dispatch class Dispatch {
class A {
public static void main(String args[]) {
void callme() {
System.out.println("Inside A's callme A a = new A(); // object of type A
method"); B b = new B(); // object of type B
}} C c = new C(); // object of type C
class B extends A {
A r; // obtain a reference of type A
// override callme()
void callme() {
r = a; // r refers to an A’s object
System.out.println("Inside B's callme r.callme(); // calls A's version of callme
method"); r = b; // r refers to a B’s object
}} r.callme(); // calls B's version of callme
class C extends A {
r = c; // r refers to a C ‘s object
// override callme()
void callme() { r.callme(); // calls C's version of callme
System.out.println("Inside C's callme }}
method"); OUTPUT:
}} Inside A's callme method
Inside B's callme method
17
Inside C's callme method
Runtime Polymorphism (7)
Discussion:
• Also, a reference of type A, called r, is declared.
• The program then assigns a reference to each type of object to r
and uses that reference to invoke callme().
• The version of callme() executed is determined by the type of
object being referred to at the time of the call.
• Had it been determined by the type of the reference variable, r,
you would see three calls to A’s callme() method.

18
Runtime Polymorphism (8)
What is the output?
class Animal{
void eat(){
System.out.println("animal is eating...");
} }
class Dog extends Animal{
void eat(){
System.out.println("dog is eating...");
} }
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}}

19
Method Overloading (1)
• Whenever same method name with different arguments in the
same class with
– different number of parameter or
– different order of parameters or
– different types of parameters is

• known as method overloading.

20
Method Overloading (2)
class Addition {
void sum(int a, int b) {
System.out.println(a+b);
}
void sum(int a, int b, int c) {
System.out.println(a+b+c);
}
public static void main(String args[]) {
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}
21
Method Overloading (3)
class Addition {
void sum(int a, int b) {
System.out.println(a+b);
}
void sum(float a, float b) {
System.out.println(a+b);
}
public static void main(String args[]) {
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}
22
Method Overriding (2)
• Whenever same method name is existing in both base class and derived
class with
– same types of parameters or same order of parameters is known as method
Overriding.

• Advantage of Method Overriding


– Method Overriding is used to provide specific implementation of a method that is
already provided by its super class.

– Method Overriding is used for Runtime Polymorphism.

• Rules for Method Overriding


– Method must have same name as in the parent class.

– Method must have same parameter as in the parent class.

– Must be IS-A relationship (inheritance).


23
Method Overriding (3)
class Walking {
void walk() {
System.out.println("Man walking fastly");
}
}
class Man extends walking {
void walk() {
System.out.println("Man walking slowly");
}
}
class OverridingDemo {
public static void main(String args[]) {
Man obj = new Man();
obj.walk();
}
}

24
Method Overriding (4)
without method overriding
class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
Output: Vehicle is running

• Problem is that you have to provide a specific implementation of run() method in


subclass that is why we use method overriding.

25
Method Overriding (5)
class Vehicle{ • In this example, we have defined the run method in
void run(){ the subclass as defined in the parent class but it has
System.out.println("Vehicle is running"); some specific implementation.
}
} • The name and parameter of the method is same and
class Bike2 extends Vehicle{ there is IS-A relationship between the classes, so
there is method overriding.
void run(){
System.out.println("Bike is running
safely"); • Whenever we are calling overridden method using
derived class object reference the highest priority is
}
given to current class (derived class).
public static void main(String args[]){
Bike2 obj = new Bike2();
• We can see in the above example high priority is
obj.run(); derived class.
}
}

Output:Bike is running safely

26
Method Overriding (6)
• Whenever we are calling overridden method using derived class
object reference the highest priority is given to current class
(derived class).
• Consider a scenario, Bank is a class that provides functionality
to get rate of interest.
• But, rate of interest varies according to banks.
• For example, Nibe, Oromia and Dashen banks could provide 8%,
7% and 9% rate of interest respectively.

27
Method Overriding (7)
class Bank{ class Test2{
int getRateOfInterest(){return 0;} public static void main(String args[]){
} Nibe s=new Nibe();
class Nibe extends Bank{ Oromia i=new Oromia();
int getRateOfInterest(){return 8;} Dashen a=new Dashen();
} System.out.println("
Nib
class Oromia extends Bank{ e Rate of Interest: "+s.getRateOfInterest());
int getRateOfInterest(){return 7;} System.out.println("
} Oromi
a Rate of Interest: "+i.getRateOfInterest());
class Dashen extends Bank{
System.out.println("
int getRateOfInterest(){return 9;} Dashe
} n Rate of Interest: "+a.getRateOfInterest());
}
}

28
Casting (1)
• In Java, type casting is a method or process that converts a one
data type into another data type in both ways manually and
automatically.
• The automatic conversion is done by the compiler and manual
conversion performed by the programmer.
Type casting and its types in the diagram

29
Casting (2)
Narrowing Type Casting: is converting a higher data type into a
lower one.
• It is also known was explicit conversion or casting up.
• It is done manually by the programmer.
• If we do not perform casting then the compiler reports a compile-
time error.

30
Casting (3)
public class NarrowingTypeCasting { //fractional part lost

public static void main(String args[]) { System.out.println("After conversion into


long type: "+ l);
double d = 12.76;
//fractional part lost
//converting double data type into long data
type System.out.println("After conversion into int
type: "+ i);
long l = (long)d;
}
//converting long data type into int data type
}
int i = (int)l;
Output
System.out.println("Before conversion: "+ d);
Before conversion: 12.76

After conversion into long type: 12

After conversion into int type: 12

31
Casting (4)
• Widening Type Casting: is converting a lower data type into a higher
one.
• It is also known as implicit conversion or casting down.
• It is done automatically. It is safe because there is no chance to lose
data. It takes place when:
– Both data types must be compatible with each other.
– The target type must be larger than the source type.
• For example, the conversion between numeric data type to char or
Boolean is not done automatically.
• Also, the char and Boolean data types are not compatible with each
other.
32
Casting (5)
public class WideningTypeCasting { output

public static void main(String[] args) { Before conversion, the value is: 8

int x = 8; After conversion, the long value is: 8

//automatically converts the integer type into long type After conversion, the float value is: 8.0

long y = x;

//automatically converts the long type into float type

float z = y;

System.out.println("Before conversion, int value "+x);

System.out.println("After conversion, long value "+y);

System.out.println("After conversion, float value "+z);

}
33
Upcasting (1)
• Upcasting in Java basically refers to the process where a subclass is converted into a superclass
reference.

• Here are the various points highlighting the concept of Upcasting in further detail below:

class Animal {

void sound() { System.out.println("Animal makes a sound"); } }

class Dog extends Animal {

void sound() {

System.out.println("Dog barks"); } }

class Cat extends Animal {

void sound() {

System.out.println("Cat meows"); }

34
Upcasting (2)
public class TestUpcasting {

public static void main(String[] args) {

Animal a; // Reference of superclass

a = new Dog(); // Upcasting (Dog is automatically upcasted to Animal)

a.sound(); // Calls the Dog class method

a = new Cat(); // Upcasting (Cat is automatically upcasted to Animal)

a.sound(); // Calls the Cat class method

Output of the code above:

Dog barks

Cat meows
35
Downcasting (1)
• Downcasting refers to a process that involves transforming a superclass reference into a
subclass reference.

• Here are the various points highlighting the concept of Downcasting below:

class Animal {

void sound() {

System.out.println("Animal makes a sound");

}}

class Dog extends Animal {

void bark() {

System.out.println("Dog barks");

}}

36
Downcasting (2)
public class TestDowncasting {

public static void main(String[] args) {

Animal a = new Dog(); // Upcasting

Dog d = (Dog) a; // Downcasting

d.sound(); // Calls the Animal class method

d.bark(); // Calls the Dog class method

}}

Output of the code:

Animal makes a sound

Dog barks

37
Questions?

38

You might also like