November 24, 202611 minutes
One line of code, many behaviors. Learn how Java decides which method runs: the compiler reads the label, the runtime opens the box.
A guitar, a drum and a piano. One loop, one call, i.play(), and yet the guitar strums, the
drum booms and the piano plinks. The compiler turned that call into a single instruction, so
who decides which play() actually runs, and when? That decision has a name: dynamic
dispatch.
Prefer to watch? The narrated video covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.
Here’s our band, written in Java:
abstract class Instrument {
void tune() { System.out.println("tuning..."); }
abstract void play();
}
class Guitar extends Instrument {
void play() { System.out.println("strum!"); }
}
class Drum extends Instrument {
void play() { System.out.println("boom!"); }
}
class Piano extends Instrument {
void play() { System.out.println("plink!"); }
void tune() { System.out.println("call a technician"); }
}We want all of them to play, and that takes just a few lines. Loop over the band and call
play() on each one:
List<Instrument> band = List.of(new Guitar(), new Drum(), new Piano());
for (Instrument i : band) {
i.play();
}The output is strum!, boom!, plink!. But look closely: there is only one call site
here. The compiler turned i.play() into a single instruction, and yet it ran three different
methods.
Which method runs is decided while the program runs, not when it compiles. That is dynamic dispatch.
Slow down and look at one line:
Instrument i = new Guitar();
i.play(); // compiles: Instrument declares play()
i.strum(); // error: Instrument has no strum()The first line mentions two different types. Think of it as a shipping box: the label on
the outside says Instrument, but inside the box there’s a guitar.
| Static type | Dynamic type | |
|---|---|---|
| In the box analogy | the label | the contents |
In Instrument i = new Guitar(); | Instrument (left of =) | Guitar (right of =) |
| Known | at compile time | only at run time |
| Decides | what you may call | what actually runs |
When you write i.play(), the compiler checks the label. Does every Instrument have a
play() method? Yes, so the code compiles. Now try i.strum(). Even if guitars could strum,
it doesn’t matter: the label says Instrument, and instruments don’t strum. That’s a compile
error.
But when i.play() actually runs, nobody reads the label anymore. The runtime opens the box,
finds a guitar, and runs Guitar.play().
The compiler reads the label. The runtime opens the box.
To see why this matters, imagine a language without dynamic dispatch. How would you make the band play? You’d have to ask each object what it is:
void perform(Instrument i) {
if (i instanceof Guitar g) g.strum();
else if (i instanceof Drum d) d.hit();
else if (i instanceof Piano p) p.press();
}If it’s a guitar, strum. If it’s a drum, hit it. If it’s a piano, press the keys. It’s like a band leader who has to ask every musician what do you play? before every single song.
And it works, until a violinist joins the band. Now the chain needs another branch:
void perform(Instrument i) {
if (i instanceof Guitar g) g.strum();
else if (i instanceof Drum d) d.hit();
else if (i instanceof Piano p) p.press();
else if (i instanceof Violin v) v.bow();
}And perform() isn’t the only place. Tuning, pricing, packing for the tour: every method that
asks what are you? needs a new branch. Miss just one, and the violin silently does
nothing: no compile error, no exception, just a missing sound.
Everything the program knows about violins ends up scattered across every method. (This is the
Switch Statements code smell in
instanceof clothing.)
So flip it around. Instead of asking the object what it is, tell it what to do. Each class
brings its own play() method (the classes from the first section): the guitar’s version
strums, the drum’s version booms, and the piano’s version plinks.
And perform shrinks to a single line:
void perform(Instrument i) {
i.play();
}The band leader just counts in, one, two, three, four, and every musician already knows their part.
Dynamic dispatch: the method that runs is chosen by the object’s class, not by the variable’s type.
A common name for this is late binding or a virtual method call. In Java, every
non-static, non-private, non-final instance method is virtual by default; in C++ or C#
you have to opt in with virtual.
How does the runtime open the box so quickly, millions of times a second? Let’s look inside the Java virtual machine.
When the compiler sees i.play(), it writes this bytecode:
aload_1
invokevirtual Instrument.play:()VNotice that it names the method from the label (Instrument.play). It has no idea a guitar
is coming.
At run time, every class gets a method table (often called a vtable), with one numbered
slot for each method that can be overridden. For Instrument, slot 0 is tune and slot 1 is
play. A subclass starts with a copy of its parent’s table. Guitar doesn’t override tune,
so slot 0 still points to the instrument’s code; but it does override play, so slot 1 now
points to Guitar.play. The drum works the same way, and the piano overrides both:
| Slot | Instrument | Guitar | Drum | Piano |
|---|---|---|---|---|
0 tune | Instrument.tune | Instrument.tune (inherited) | Instrument.tune (inherited) | Piano.tune |
1 play | (abstract) | Guitar.play | Drum.play | Piano.play |
Every object also carries a hidden pointer to its class. So a call works like this:
i to the object.Run the whole band and the same slot, in three different tables, gives three different methods. The work is split in two:
A few details the picture simplifies. Real JVM tables start with the methods inherited from
Object (toString, equals, hashCode, …) before tune and play. Calls through an
interface type compile to invokeinterface, which uses a slightly different lookup (interface
tables, because one class can implement many interfaces). And the JVM specification only
defines what invokevirtual must find; vtables are how HotSpot and most other JVMs implement
it.
Here’s why this matters so much in real code. A violin joins the band, so we write one new class:
class Violin extends Instrument {
void play() { System.out.println("vibrato!"); }
}Now look at the loop from the very beginning. We didn’t touch it. We didn’t even recompile it.
And yet, when the band includes a Violin, it prints vibrato!.
You’re on the other side of this all the time. Give the guitar a toString() method, print it,
and out comes the word Guitar:
class Guitar extends Instrument {
void play() { System.out.println("strum!"); }
@Override
public String toString() { return "Guitar"; }
}
System.out.println(new Guitar()); // prints: Guitarprintln calls String.valueOf, which calls toString() on your object. That code lives in
the JDK and was written years before your Guitar class existed. Dispatch finds your method
anyway:
Old code, calling new code. Frameworks, plugins and libraries are all built on this: a servlet
container calls your doGet, a sort calls your compareTo, a test runner calls your test
methods. You add a new type, and nobody else has to change. It’s also what makes patterns
like
State work: the context just calls state.pressButton()
and whichever state object is plugged in answers.
Now a classic trap. Not everything you reach through a variable is dispatched:
class Instrument {
String name = "instrument";
static String family() { return "generic"; }
}
class Guitar extends Instrument {
String name = "guitar";
static String family() { return "strings"; }
}
Instrument i = new Guitar();
System.out.println(i.name); // instrument
System.out.println(i.family()); // genericBoth classes declare a field called name and a static method called family. We create a
guitar, put an Instrument label on it, and print both. You might expect guitar and
strings. Instead, you get instrument and generic.
Fields and static methods are picked by the compiler, straight off the label. The same goes
for private methods, constructors, and calls through super. Only methods that can be
overridden ever open the box.
A field in a subclass doesn’t override the parent’s field; it hides it. (Calling a static
method through an instance, as in i.family(), compiles but gets a warning in most IDEs for
exactly this reason; write Instrument.family().) If something should change from class to
class, make it a method.
One more trap, and it’s the one that catches almost everyone: overloading.
class Tuner {
void check(Instrument i) { System.out.println("generic check"); }
void check(Guitar g) { System.out.println("guitar check"); }
}
Instrument i = new Guitar();
new Tuner().check(i); // generic checkThis tuner has two check methods with the same name: one takes any instrument, the other
takes a guitar. We pass it a guitar. Which one runs? Generic check. Surprised? Choosing
between overloads happens at compile time. The compiler reads the argument’s label, sees
Instrument, and locks in check(Instrument).
| Overriding | Overloading | |
|---|---|---|
| Same name, … | same parameters, in a subclass | different parameter types |
| Chosen by | the receiver (object before the dot) | the arguments |
| Looks at | dynamic type (contents) | static types (labels) |
| When | run time | compile time |
Overriding picks a method by the receiver at run time. Overloading picks by the arguments at compile time. Java only dispatches dynamically on one thing: the receiver. That’s called single dispatch.
So how do we get the guitar check? We let the guitar call the tuner itself:
abstract class Instrument {
abstract void accept(Tuner t);
}
class Guitar extends Instrument {
void accept(Tuner t) { t.check(this); } // here, this is a Guitar
}
i.accept(new Tuner()); // guitar checki.accept(...) is dispatched on the instrument, so we land inside
Guitar.accept.Guitar, this is labeled Guitar, so the compiler picks
check(Guitar).Two hops, so it’s called double dispatch. It’s the trick behind the Visitor pattern.
The receiver is dynamic. The arguments are static.
Lean on dynamic dispatch when new types keep arriving and the operations stay the same, like new instruments joining the band. Each new type is just one new class; no existing code changes.
Sometimes it’s the other way around. The list of types stays fixed, and you keep adding
operations: insurance, shipping, pricing. Putting every operation into every class then
bloats the hierarchy. A sealed class with a pattern-matching switch (Java 21) can be
clearer, because the compiler checks that you’ve covered every case:
sealed abstract class Instrument permits Guitar, Drum, Piano { }
String insurance(Instrument i) {
return switch (i) {
case Guitar g -> "low";
case Drum d -> "medium";
case Piano p -> "high";
};
}Unlike the instanceof chain from earlier, this switch has no default branch, so adding a
Violin to the permits list turns every incomplete switch into a compile error instead of a
silent bug. (This trade-off, types versus operations, is known as the expression problem.)
A common worry: aren’t these calls slow? Rarely. The just-in-time (JIT) compiler watches
which classes actually show up at each call site. If a call site only ever sees guitars, it
skips the table and calls Guitar.play() directly (often inlining it), keeping a cheap type
check as a guard. Call sites that see a few classes stay fast too; only truly megamorphic
sites pay for the table lookup, and even that costs a couple of memory loads.
The label is the static type: it tells the compiler what you may call, and fixes the slot. The contents are the dynamic type: at run time the object points to its class, the class’s table gives the slot, and the slot gives the code.
super calls are not dispatched.switch when operations do.One line of code, many behaviors. The compiler reads the label. The runtime opens the box.