Dynamic Method Dispatch in Java

Dynamic method Dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.

Dynamic method dispatch allows java to support overriding of methods and perform runtime polymorphism.It allows subclasses to have common methods and can redefine specific implementation for them. This lets the superclass reference respond differently to same method call depending on which object it is pointing.

  • When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time.
  • At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed
  • A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java uses this fact to resolve calls to overridden methods at run time.



package com.ritesh;
class phone{
public void call(){
System.out.println("Calling in phone.......");
}
public void hello(){
System.out.println("Welcome to the phone");
}

}

class smartphone extends phone{
public void call(){
System.out.println("Calling in smartphone....");
}
public void music(){
System.out.println("Playing music..");
}

}

public class DynamicMemory_Dispatch {
public static void main(String[] args) {
//Dynamic Method Dispatch in Java
phone p1=new smartphone();
p1.call(); //if you call this method then method on smartphone class will call.
//so simply it will print calling in smartphone.
p1.hello();

}
}

Comments