Dynamic Dispatch
in Java
Learn how Java decides which method to call at runtime, enabling polymorphism and flexible object-oriented design.
What Is Dynamic Dispatch?
When you call a method on an object in Java, the JVM must decide which version of that method to execute. Dynamic dispatch is the mechanism by which this decision is made at runtime, based on the actual type of the object: not the declared type of the variable holding it.
Key Vocabulary
Why Does It Matter?
The Core Rule
How the JVM Resolves a Call
Static vs Dynamic Binding
| Static Binding | Dynamic Binding | |
|---|---|---|
| When resolved | Compile time | Runtime |
| Applies to | Overloaded methods, static methods, private methods | Overridden instance methods |
| Based on | Declared (reference) type | Actual (object) type |
| Keyword clue | static, private, final | Instance methods + inheritance |
| Performance | Slightly faster (no lookup) | Tiny overhead (vtable lookup) |
How to Trace a Method Call
Example 1: Basic Dispatch
Example 2: Three-Level Hierarchy
Example 3: Interfaces and Dispatch
The Catch: Fields Are Not Dispatched
Static Methods: No Dispatch
Dispatch Walk-Up Diagram
Common Mistakes
Summary Reference
| Feature | Binding | Based On |
|---|---|---|
| Instance methods (overridden) | Dynamic (runtime) | Actual type |
| Static methods | Static (compile time) | Declared type |
| Private methods | Static (compile time) | Declared type |
| Final methods | Static (compile time) | Declared type |
| Fields (instance variables) | Static (compile time) | Declared type |
| Overloaded methods | Static (compile time) | Declared type + parameter types |
Question 1 of 5
class Animal { void speak() { System.out.println("..."); } }
class Cat extends Animal { void speak() { System.out.println("Meow"); } }
Animal a = new Cat();
a.speak();
What is the output of a.speak()?
Question 2 of 5
class A { static void hello() { System.out.println("A"); } }
class B extends A { static void hello() { System.out.println("B"); } }
A obj = new B();
obj.hello();
What is the output of obj.hello()?
Question 3 of 5
Which of the following is required for dynamic dispatch to occur in Java?
Question 4 of 5
class X { String tag = "X"; String getTag() { return "X"; } }
class Y extends X { String tag = "Y"; String getTag() { return "Y"; } }
X obj = new Y();
System.out.println(obj.tag + " " + obj.getTag());
What is the output?
Question 5 of 5
class Musician { void play() { System.out.println("Music"); } }
class Guitarist extends Musician { /* no override */ }
class Bassist extends Musician { void play() { System.out.println("Bass"); } }
Musician m = new Guitarist();
m.play();
What is the output of m.play()?