How does dynamic method dispatch work in Java, and what exactly does the runtime look at?
Dynamic method dispatch is the rule that when you call a method on an object, the runtime looks at the actual object and runs the version of the method that belongs to that object's class.
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.speak()); // woof
}
}
And here is the parent and the child.
public class Animal {
public String speak() {
return "...";
}
}
public class Dog extends Animal {
@Override
public String speak() {
return "woof";
}
}
So what exactly does the runtime look at? Three things, in this order.
the step what the runtime does
---------------------------- --------------------------------------------
1. the class of the object it finds the class that the object
really is, which is Dog
2. the method in that class it looks for speak in Dog, and it
finds it
3. the parent if it is not if the class does not have the
there method then it goes up the chain
And the third step is worth knowing about, because it is the difference between overriding and hiding. If Dog did not have a speak method then the runtime would go up to Animal and use that one. So the search goes from the actual class upwards until it finds the method.
And there is one important detail about the compile step that comes before this. When the compiler sees a.speak() it checks that the method exists in the declared type, which is Animal. So the compiler only allows the call if Animal has the method. Then at runtime the object decides which version runs.
at compile time at run time
---------------------------- ------------------------------
the declared type is Animal the object is really a Dog
so the call is allowed so Dog.speak runs
And the runtime does not look at the declared type at all. It only looks at the object. That is why you can hold an Animal in a variable and get a Dog's behaviour out of it.
And there is one thing that is worth knowing about, and it is the exact rule that decides whether the runtime even looks. A method is dispatched dynamically unless it is static, final or private. So a static method is picked at compile time, a final method cannot be overridden so it is picked at compile time, and a private method cannot be overridden so it is picked at compile time.
the method is it dispatched at run time
---------------- --------------------------------
public yes
protected yes
package-private yes
private no, it cannot be overridden
static no, it is picked by the type
final no, it cannot be overridden
So the rule to remember is this. The runtime looks at the class of the object and searches upwards until it finds the method.
The last question in this topic is about why the declared type still matters.