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
Example showing dynamic dispatch with instance and static method.
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.