"dispatch" ~ "determining which method to call".
"dynamic" part ~ it is "determined at runtime". Which method is to be called is determined at runtime.
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time which we would require when we have used inheritance/ polymorphism
When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to.
class Pizza {
int price = 200;
public void display() {
System.out.println("In Pizza");
}
}
class Margherita extends Pizza {
int price = 180; //super class data members can't be overridden
public void display() {
System.out.println("In Margherita");
}
}
class Veggie extends Pizza {
public void display() {
System.out.println("In Veggie");
}
}
public class DynamicMethodDispatch {
public static void main(String[] args) {
Pizza pizza = new Pizza();
pizza.display();
pizza = new Margherita();
pizza.display();
System.out.println(pizza.price);
pizza = new Veggie();
pizza.display();
}
}
Output:
In Pizza
200
In Margherita
200
In Veggie
In the above code snippet, creating the reference of parent class Pizza, it is in hands of Java now, to finalize which version of the display() method needs to be invoked based on the type of object created whether it is Margherita or Veggie in our case.
Note: Only super class methods can be overridden in subclass, data members of super class cannot be overridden.
When Parent class reference variable refers to Child class object, it is known as Upcasting. In Java this can be done and is helpful in scenarios where multiple child classes extends one parent class. In those cases we can create a parent class reference and assign child class objects to it.
Comments