Dynamic method dispatch is a way to resolve overridden method calls at run time instead of compile time. It is based on the concept of up-casting. Up-casting means “A super class reference variable can refer to subclass object”.
Java Dynamic Method Dispatch Example
package com.w3schools;
class Engineer {
public void show(){
System.out.println("Engineer details.");
}
}
public class SoftwareEngineer extends Engineer{
public void show(){
System.out.println("Software Engineer details.");
}
public static void main(String args[]){
Engineer obj = new SoftwareEngineer();
//Method call will be resolved at runtime.
obj.show();
}
}
Output:
Software Engineer details.
Note: Only superclass methods can be overridden in a subclass, data members of the super class cannot be overridden.
package com.w3schools;
class Engineer {
int eId = 20;
}
class SoftwareEngineer extends Engineer {
int eId = 50;
}
class DevOpsEngineer extends SoftwareEngineer {
int eId = 60;
}
public class EngineerTest {
public void show(){
System.out.println("Software Engineer details.");
}
public static void main(String args[]){
//Superclass can contain subclass object.
Engineer obj1 = new SoftwareEngineer();
Engineer obj2 = new DevOpsEngineer();
//In both calls eId of superclass will be printed.
System.out.println(obj1.eId);
System.out.println(obj2.eId);
}
}
Output:
20 20