What is dynamic method dispatch in Java, and how does the JVM decide which implementation to run?
Dynamic method dispatch is the rule that says the version of an overridden method that runs is chosen at run time, based on the object that the reference actually points at.
When the virtual machine calls a method on an object, it looks at the real type of that object, not at the type of the variable that holds it. If that real type has its own version of the method, that version runs. If it does not, the version of the nearest parent that has one runs.
This is what makes polymorphism work. You can write one method that takes an Animal, and it will do the right thing for a dog, a cat and a bird, without ever mentioning any of them.
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
// The Dog version runs, because the object really is a Dog.
System.out.println(animal.speak());
// A method that is not overridden runs the parent's version.
System.out.println(animal.describe());
}
}
class Animal {
String speak() {
return "...";
}
String describe() {
return "an animal";
}
}
class Dog extends Animal {
@Override
String speak() {
return "woof";
}
}
There is a limit to this, and it is worth knowing. Dispatch only happens for instance methods. A static method is resolved at compile time from the type of the name that you used, and a private method is not inherited at all, so neither of them is dispatched.
The next question in this topic looks at the difference between the type of the reference and the type of the object.