Java-Runtime Polymorphism or Dynamic Method Dispatch

Runtime Polymorphism or Dynamic Method Dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time. A superclass reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here is how. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. When different types of objects are referred to, different versions of an overridden method will be called.

In other words, it is the type of the object being referred to that determines which version of an overridden method will be executed. Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed.

Program

1

Program Source

class DataV1 {
    
    int data1;
    int data2;
    
    void dataValues()
    {
        System.out.println("data1 = "+data1);
        System.out.println("data2 = "+data2);
    }
}

class DataV2 extends DataV1 {
    
    int data3;
    int data4;
    
    void dataValues()
    {
        System.out.println("data3 = "+data3);
        System.out.println("data4 = "+data4);
    }
}

class DataV3 extends DataV1 {
    
    int data5;
    int data6;
   
    void dataValues()
    {
        System.out.println("data5 = "+data5);
        System.out.println("data6 = "+data6);
    }
}

public class Javaapp {
    
    public static void main(String[] args){
        
        DataV1 a = new DataV1();
        a.data1 = 10;
        a.data2 = 20;
        DataV2 b = new DataV2();
        b.data3 = 30;
        b.data4 = 40;
        DataV3 c = new DataV3();
        c.data5 = 50;
        c.data6 = 60;
        
        DataV1 refer;
        refer = a;
        refer.dataValues();
        refer = b;
        refer.dataValues();
        refer = c;
        refer.dataValues();
   }
}

Leave a Comment