Run time polymorphism

Run time polymorphism

  •  In run time polymorphism method body is binded to method implementation at run time based on instance created.
  • This type of binding known as dynamic binding or late binding.
  • Method overriding is example of run time polymorphism.
  • To achieve run-time polymorphism we need to full feel following concept
    1. Inheritance
    2. Method overriding
    3. Up casting
  •  With the help of run time polymorphism you can achieve
    – Generalization
    – Abstraction
    – Loose coupling

 

Step to achieve Run time polymorphism
1. Object implementation layer
2. Object creation layer
3. Object utilization layer.

 Object implementation layer

  •  In this layer object implementation done by using abstraction principle.
  •  Generalize the common behavior in an interface and provide implementation to specific class

 Object creation layer

  • In this layer the object required is created based on need by using factory pattern.
  •  The created object casted to interface type and returned.

 Object utilization layer.

  •  In this layer functionality of object is used without knowing how it is
    implemented.
  •  Object is reference through interface reference variable.

Program to achieve Run time polymorphism

public interface Vehicle
{
//GENERALIZE THE COMMON BEHAVIOR IN INTERFACE

void start();
void move();
void stop();

}

class Bike implements Vehicle
{

public void start()
{

System.out.println("starting bike");
}

public void move()
{

System.out.println("moving bike");
}

public void stop()
{
System.out.println("stoping bike");

}

}

class Car implements Vehicle
{

public void start()
{
System.out.println("starting car");
}

public void move()
{

System.out.println("moving car");
}

public void stop()
{
System.out.println("stoping car");
}

}

//object creating
class Person
{

Vehicle v;
void initvehicle(Vehicle v)
{
this.v=v;//OBJECT IS CASTED TO INTERFACE TYPE

}

void compute()
{
v.start();
v.move();
v.stop();

}

}

//object utilizing

class Mainclass
{
public static void main(String[] args)
{

System.out.println("*******************************");

Person p=new Person();

//utilizing object functionality without knowing how it is implemented
p.initvehicle(new Car());

//HERE WE USE CAR OBJECT WITHOUT KNOWING HOW IT IS IMPLEMENTED

p.compute();

System.out.println("*******************************");

p.initvehicle(new Bike());
p.compute();

System.out.println("*******************************");
}

}

output:

*******************************
starting car
moving car
stoping car
*******************************
starting bike
moving bike
stoping bike
*******************************

 

Leave a Reply