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.

Upcasting:

When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:
class A{}
class B extends A{}
class Test{
   public static void main(String args[]){
   A a=new B();//upcasting
  }
}

Example of Runtime Polymorphism:

In this example, we are creating two classes Bicycle and HondaShine. HondaShine class extends Bicycle class and overrides its run() method. We are calling the run 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 Bicycle{
   void run(){
   System.out.println("bicycle is running");
   }
 }
 class HondaShine extends Bicycle{
   void run(){
     System.out.println("shine is running safely with 70km");
    }
 
   public static void main(String args[]){
     Bicycle b = new HondaShine();//upcasting
     b.run();
   }
 }

Output:
shine is running safely with 70km

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 speedlimit, 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.

class Bicycle{
  int speedlimit=100;
 }
 class HondaShine extends Bicycle{
  int speedlimit=160;
 
  public static void main(String args[]){
   Bicycle obj=new HondaShine();
   System.out.println(obj.speedlimit);
 }
}

Output:
100

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



<<Previous <<   || Index ||   >>Next >>


No comments:

Post a Comment