Dynamic dispatch is a process of selecting, which methods to call at run-time. It is a mechanism by which a call to overridden method at run time is resolved rather then compile time.
Dynamic method dispatch
Dynamic dispatch is a process of selecting, which methods to call at run-time. It is a mechanism by which a call to overridden method at run time is resolved rather then compile time. Method of execution is based upon the type of object being referred. By this run-time polymorphism is achieved in java. Let suppose a class A contain a method display() ,class B extends A and override method display, we generally create a object of parent class or child class or reference variable of parent class. Now we are creating a reference of parent class through which we call parent class method and child class method as well.
Example : How to implement dynamic dispatch in java
class A { public void display() { System.out.println("In class A"); } } class B extends A { public void display() { System.out.println("In class B"); } } public class Dynamicdispatch { public static void main(String args[]) { A ob=new A(); B ob2=new B(); A r; //obtain a reference of type A r=ob; //r refer to A object r.display(); //call display() method of A r=ob2; //r refer to b object r.display(); //call display() method of B System.out.println("In main Class"); } }
Description : In the above example we are creating a reference of class A and through the reference of parent class that is A we used to refer the child class methods. and also parent class methods.
Output : After compiling and executing the above program