Dynamic Method Dispatch Concept Simplified in Java


Methods can be called in java dynamically.Whenever a method is called on an Object reference,the declared type object reference is checked at compile time to make sure that the method definition exists in the declared class.At run time the object reference could be referring to an instance of some subclass of the declared reference type.
This phenomenon is referred as Dynamic Method Dispatch in java.
An Example

public class WhoTest{

     public static void main(String []args){
        A a=new B();
        a.call();
     }
}
class A{
    void call(){
        System.out.println("From A");
    }
}
class B extends A{
    void call(){
        System.out.println("From B");
    }
}
 
Output of the code:
$javac WhoTest.java
$java -Xmx128M -Xms16M WhoTest
From B
Here we have declared a variable to be of type A but stores reference to an instance of class B.When we call a method call(),java notices that the reference is actually an instance of class B. So it calls Class B's call() method instead of A's.This helps to ensure reusability and robustness.This is how we call methods from libraries on instance of new classes without recompiling while maintaining a class as abstract interface.
Dynamic Method Dispatch Concept Simplified in Java Dynamic Method Dispatch Concept Simplified in Java Reviewed by Animesh Chatterjee on October 16, 2018 Rating: 5

No comments:

Powered by Blogger.