This page topics close

Dynamic Method Dispatch is a mechanism by which a call to an overridden method of Parent class is resolved at run time rather than compile time.

Dynamic Method Dispatch is a way of implementing Run-Time polymorphism in java.

  • Example of Dynamic Method Dispatch

    • Super class reference variable can refer child class object. for example
      Parent p=new Child();

    • Whenever an overridden method is called through the parent class reference variable , java determines which method body to execute based upon the object contained by reference variable at run time. This is what exactly method body resolution is.

    Let us see the example to understand above points.


    Example

    
    class A {
    	void show() {
    		System.out.println("A 's show()");
    	}
    }
    
    class B extends A {
    	void show() {
    		System.out.println("B 's show");
    	}
    }
    
    class C extends A {
    	void show() {
    		System.out.println("c 's show");
    	}
    }
    
    public class Executor {
    	public static void main(String[] args) {
    		A ob = new B();// Parent(A) class can refer Child(B) object
    		A ob1 = new C();// Parent(A) class can refer Child(C) object
    		ob.show();// calls show() of B
    		ob1.show();// calls show() of C
    	}
    }

    Output:
    B 's show
    c 's show
    

What next?

Share this page