It is a concept in java to achieve the Dynamic / Run-time polymorphism. It is the process of assigning sub-class object in super type reference later if needed that sub-class object can be type-caste into its super type. Dynamic dispatch can be achieved only with the instance member.

Important point regarding dynamic dispatch

1. If we are trying to access instance member with dynamic dispatch concept then it will access sub-class overridden method.

2. If we are trying to access static member with the dynamic dispatch concept then it will access super-class method as because compiler internally replace the super-class reference variable with its class name.

Example showing dynamic dispatch with instance and static method.

class B {

 public static void display(){
  System.out.println("super-class static method");
 }
 public void add(){
  System.out.println("super-class instance method");
 }
}

public class A extends B{
 
 public static void display(){
  System.out.println("sub-class static method");
 }
 public void add(){
  System.out.println("sub-class instance method");
 }
 
 public static void main(String[] args) throws Exception {
  
  B b = new A(); // Dynamic dispatch 
  b.display();  // Calling static method
  b.add();     // Calling instance method
 }

}

In the above code the statement B b = new A() is used to store sub-class in its super-class and tried to access static method " display " which will super-class display() method as because compiler internally convert the b.display() into B.display() but in case of instance it will access with the object only that's why it call the overridden method in sub-class. 

Note : The same will happen with the static and instance variable. With dynamic dispatch concept accessing static variable will access super-class static variable but accessing instance variable will access sub-class instance variable.  

4 comments:

  1. sir plz explain this more clearly by considering the fact that what problems faced here becoz according to me there should be no problem if i write subclass object=new superclass() so i can clearlycall the parents method then why do they call it to be dyanmic and what if from child class i want to call its grand-parent class method

    ReplyDelete
    Replies
    1. Subclass Object = new SuperClass() is not possible.

      Delete
  2. Great, thanks for sharing this post.Much thanks again. Awesome.
    core java online course
    core java online training

    ReplyDelete

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic