Friday, 19 December 2014

What is Runtime Polymorphism in java


Runtime Polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.
In this process, 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.

Example of Runtime Polymorphism:

In this example,we are creating two classes Car and Honda. Honda class extends Car class and
overrides its runing() method.We are calling the runing method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent
class method, subclass method is invoked at runtime. Since it is determined by the compiler,
which method will be invoked at runtime, so it is known as runtime polymorphism.

class Car{
void runing(){System.out.println("running");}
}
class Honda extends car{
void runing(){
System.out.println("car is running ");
}
public static void main(String []args){
Honda h = new Car();
h.runing();
  }
}

Output: car is running

Runtime Polymorphism with data member

Method is overriden not the datamembers,so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speed, we are accessing the
datamember by the reference variable of Parent class which refers to the subclass object. Since we are
accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

Note: Runtime polymorphism can't be achieved by data members.

class Car {
int speed=50;
}
class Honda extends Car{

int speed=80;
public static void main(String []args){
Car c=new Honda();
System.out.println(c.speed);
   }
}

Output: 50

No comments:

Post a Comment