Dynamic Method Dispatch in Java

  • 0
Dynamic Method Dispatch is the mechanism in which call to an overridden method is resolved at run time rather than at compile time. Dynamic Method Dispatch is related to a principle that states that an super class reference can store the reference of subclass object. However, it can't call any of the newly added methods by the subclass but a call to an overridden methods results in calling a method of that object whose reference is stored in the super class reference. It simply means that which method would be executed, simply depends on the object reference stored in super class object.
I have written a program that clearly explains above stated principle.
package ClassIllustration;

class A
{
 void callme()
 {
  System.out.println("Inside A's callme Method");
 }
}
class B extends A
{
 void callme()
 {
  System.out.println("Inside B's callme Method");
 }
}
class C extends B
{
 void callme()
 {
  System.out.println("Inside C's callme Method");
 }
}

class DynamicMethodDispatch
{
 public static void main(String args[])
 {
  A a = new A();
  B b = new B();
  C c = new C();
  
  A r;
  r = a;
  r.callme();
  
  r = b;
  r.callme();
  
  r = c;
  r.callme();
 }
}
As you can see, Reference of class A stores the reference of class A, class B and class C alternatively. Every call to callme() method would result in execution of callme() method of that class whose reference is currently stored by a reference of class A. To compile the program
javac -d . DynamicMethodDispatch.java
And to run the program
java ClassIllustration.DynamicMethodDispatch
Here is the output that I received on executing this program on my machine
Inside A's callme Method
Inside B's callme Method
Inside C's callme Method

No comments:

Post a Comment