Sub topic 5
How Java Picks the Method at Runtime
In the last few chapters you saw two ideas. First, a variable of type Animal can hold a Dog or a Cat. Second, a subclass can override a method it inherits. This chapter puts the two together and answers one question: when you call a method through a variable, which version of the method runs?
The answer has a name: dynamic method dispatch. Dynamic method dispatch is the rule Java uses to choose an overridden method while the program is running. Java looks at the real object, not the variable's type. Because of this rule, one line of code can do different things for different objects. That is what runtime polymorphism means.
The Two Questions Java Asks
Every method call such as a.sound() goes through two checks, and each check happens at a different time.
- At compile time, the compiler asks: "Does the declared type have a method called
sound()?" The declared type is the type written next to the variable, likeAnimalinAnimal a. If the answer is no, the program does not compile. - At runtime, the JVM asks: "What is the actual class of the object in
a?" The runtime type is the class used withnewwhen the object was made. The JVM runs the version ofsound()that belongs to that class.
So the declared type decides whether you may call a method. The runtime type decides which version runs.
| Question | Who answers it | When | Based on |
|---|---|---|---|
| Is this call allowed? | The compiler (`javac`) | Compile time | Declared type of the variable |
| Which version runs? | The JVM | Runtime | Actual class of the object |
A First Example
Here is a complete program. Save it as Main.java, then compile and run it with javac Main.java and java Main.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
class Cat extends Animal {
@Override
String sound() {
return "Meow";
}
}
public class Main {
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Animal() };
for (Animal a : animals) {
System.out.println(a.sound());
}
}
}Output:
Woof
Meow
...The loop variable a has the declared type Animal every time. The line a.sound() never changes. Even so, the output changes, because each pass through the loop puts a different object in a. The JVM checks each object's real class and runs that class's sound().
How the JVM Searches for a Method
What happens if the object's class does not override the method? The JVM does not give up. It searches upward through the class's parents until it finds a version.
The search works like this:
- Start at the object's actual class.
- If that class defines the method, run it. Stop.
- If not, move to its superclass (its parent class) and check again.
- Repeat until a version is found.
The search always succeeds. The compiler already checked that the declared type has the method, and the object's class is that type or one of its subclasses, so a version exists somewhere on the way up.
Let's watch the search in action. Puppy extends Dog but does not override anything.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
class Puppy extends Dog {
// No methods of its own
}
public class Main {
public static void main(String[] args) {
Animal a = new Puppy();
System.out.println(a.sound()); // Woof
}
}The JVM starts at Puppy and finds no sound(). It moves up to Dog, finds sound(), and runs it. The program prints Woof. The search stops at the first match, so Animal's version is never reached.
Dispatch Also Works Inside Methods
Dynamic dispatch is not just for calls written in main. It also applies when one method calls another inside a class. Inside a method, a call like sound() really means this.sound(). The word this refers to the current object, and that object still has its real runtime type.
class Animal {
String sound() {
return "...";
}
String speak() {
return "I say " + sound();
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.speak()); // I say Woof
}
}Follow the steps:
a.speak(): the JVM starts atDog.Doghas nospeak(), so it moves up toAnimaland runsAnimal.speak().- Inside
speak(), the callsound()meansthis.sound(). The object inthisis still aDog. - The JVM starts the search at
Dogagain and findsDog.sound(), which returns"Woof".
So Animal's code ends up calling Dog's method. Code written in the parent class can use behavior that a child class supplies later.
The Declared Type Still Limits What You Can Call
The runtime type picks the version, but it cannot add new methods to the variable. Suppose Dog has an extra method that Animal lacks:
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
void fetch() {
System.out.println("Fetching!");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.sound()); // allowed: Animal has sound()
// a.fetch(); // compile error: Animal has no fetch()
}
}If you remove the // before a.fetch();, the compiler reports cannot find symbol. The object really is a Dog, but the compiler only looks at the declared type Animal. It cannot be sure what object will be in a when the program runs, so it allows only the methods every Animal has. A later chapter shows how to get the Dog back safely when you need fetch().
Why This Is Useful
Dynamic dispatch lets you write code once and have it work with classes that do not exist yet. Look at this method:
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
class Cow extends Animal {
@Override
String sound() {
return "Moo";
}
}
public class Main {
static void chorus(Animal[] animals) {
for (Animal a : animals) {
System.out.println(a.sound());
}
}
public static void main(String[] args) {
chorus(new Animal[] { new Dog(), new Cow() });
}
}The chorus method knows nothing about Dog or Cow. Suppose you add a Cow class next year. chorus still works with it, and you do not change a single line inside chorus. Without dispatch you would need a long if chain that checks each type by hand, and you would have to update it every time someone adds a new animal.
Summary
- Each method call goes through two checks. The compiler uses the declared type to decide if the call is allowed. The JVM uses the runtime type to decide which version runs.
- The JVM starts at the object's actual class and moves up through superclasses until it finds the method.
- Calls inside a method go through
this, so they dispatch on the real object too. - The declared type limits which methods you can call, even if the object has more.
Exercise
Given class A { String hi() { return "A"; } String greet() { return "Hello " + hi(); } }, class B extends A { @Override String hi() { return "B"; } }, and class C extends B { }, what does this print: A x = new C(); System.out.println(x.greet());
Show answer
It prints "Hello B". The JVM starts at C, finds no greet(), and checks B, which also has none. It then runs A.greet(). Inside greet(), hi() means this.hi(), and this is a C object. The search starts at C again, finds no hi(), and moves up to B.hi(), which returns "B".
Exercise
A variable is declared as Animal a = new Dog(); and Dog defines a method fetch() that Animal does not have. Why does a.fetch() fail to compile even though the object is a Dog?
Show answer
The compiler checks calls against the declared type, Animal, and Animal has no fetch() method. The compiler cannot know which object will be in a at runtime, so it only allows methods that every Animal has. Dynamic dispatch only chooses among versions of methods the declared type already has.
Exercise
In the Puppy example, Puppy extends Dog, Dog overrides sound() to return "Woof", and Animal's sound() returns "...". If Dog's override were deleted, what would new Puppy().sound() return when called through an Animal variable, and why?
Show answer
It would return "...". The JVM starts at Puppy and finds no sound(), then checks Dog and finds none, then reaches Animal and runs Animal's version.