Dynamic Dispatch

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.

One line, three behaviors

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.

The single call site i.play() leads, at run time, to three different methods: Guitar.play prints strum, Drum.play prints boom, Piano.play prints plink. The single call site i.play() leads, at run time, to three different methods: Guitar.play prints strum, Drum.play prints boom, Piano.play prints plink.
One call site, compiled once, three methods at run time.

Which method runs is decided while the program runs, not when it compiles. That is dynamic dispatch.

The label and the contents

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.

  • The type on the label is the static type. It’s the declared type of the variable, and it’s all the compiler can see.
  • The type of what’s inside is the dynamic type. It only exists at run time, once the object has actually been created.
Static typeDynamic type
In the box analogythe labelthe contents
In Instrument i = new Guitar();Instrument (left of =)Guitar (right of =)
Knownat compile timeonly at run time
Decideswhat you may callwhat 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().

Two stages. At compile time the compiler reads the label Instrument and checks that play() exists, while strum() is rejected. At run time the JVM opens the box, finds a Guitar and runs Guitar.play. Two stages. At compile time the compiler reads the label Instrument and checks that play() exists, while strum() is rejected. At run time the JVM opens the box, finds a Guitar and runs Guitar.play.
The compiler reads the label. The runtime opens the box.

The compiler reads the label. The runtime opens the box.

The obvious way: ask what it is

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.

Adding the Violin class forces a new instanceof branch in perform, tuneAll, price and pack. The branch in pack was forgotten, so the violin silently does nothing there. Adding the Violin class forces a new instanceof branch in perform, tuneAll, price and pack. The branch in pack was forgotten, so the violin silently does nothing there.
One new type, edits everywhere.

Everything the program knows about violins ends up scattered across every method. (This is the Switch Statements code smell in instanceof clothing.)

The key insight: tell, don’t ask

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.

Before: perform asks the object what it is through an instanceof chain with one branch per class. After: perform calls i.play and each class supplies its own play method. Before: perform asks the object what it is through an instanceof chain with one branch per class. After: perform calls i.play and each class supplies its own play method.
Ask, then branch (top) versus tell, and let the class answer (bottom).
Class diagram: abstract class Instrument with tune and abstract play. Guitar, Drum and Piano extend it and override play; Piano also overrides tune. Class diagram: abstract class Instrument with tune and abstract play. Guitar, Drum and Piano extend it and override play; Piano also overrides tune.

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.

Under the hood: one table per class

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:()V

Notice 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:

SlotInstrumentGuitarDrumPiano
0 tuneInstrument.tuneInstrument.tune (inherited)Instrument.tune (inherited)Piano.tune
1 play(abstract)Guitar.playDrum.playPiano.play

Every object also carries a hidden pointer to its class. So a call works like this:

  1. Follow the variable i to the object.
  2. Follow the object’s class pointer to its class.
  3. Take slot 1 of that class’s table.
  4. Jump.
The call path: variable i, whose label is Instrument, points to a Guitar object; the object's class pointer leads to the Guitar method table; slot 1 of that table leads to Guitar.play, which prints strum. The call path: variable i, whose label is Instrument, points to a Guitar object; the object's class pointer leads to the Guitar method table; slot 1 of that table leads to Guitar.play, which prints strum.
The compiler picks the slot; the object picks the table.

Run the whole band and the same slot, in three different tables, gives three different methods. The work is split in two:

  • The compiler picks the slot, from the label (static type).
  • The object picks the table, from its class (dynamic type).

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.

Old code calls new code

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: Guitar

println 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:

Sequence: your code calls PrintStream.println with a Guitar; println calls String.valueOf; valueOf calls x.toString, which is dispatched to Guitar.toString in your code and returns the string Guitar. Sequence: your code calls PrintStream.println with a Guitar; println calls String.valueOf; valueOf calls x.toString, which is dispatched to Guitar.toString in your code and returns the string Guitar.
JDK code (java.base) calling your override.

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.

What is not dispatched

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());   // generic

Both 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.

Decision: is the member an overridable instance method? Yes means it is dispatched at run time from the object's class. No, which covers fields, static methods, private methods, constructors and super calls, means it is resolved at compile time from the label. Decision: is the member an overridable instance method? Yes means it is dispatched at run time from the object's class. No, which covers fields, static methods, private methods, constructors and super calls, means it is resolved at compile time from the label.
Label or contents?

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.

Overloading vs overriding

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 check

This 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).

OverridingOverloading
Same name, …same parameters, in a subclassdifferent parameter types
Chosen bythe receiver (object before the dot)the arguments
Looks atdynamic type (contents)static types (labels)
Whenrun timecompile time
For the call new Tuner().check(i): at compile time the overload check(Instrument) is fixed from the argument's label; at run time only the receiver's class is looked up, which finds Tuner.check(Instrument), printing generic check. For the call new Tuner().check(i): at compile time the overload check(Instrument) is fixed from the argument's label; at run time only the receiver's class is looked up, which finds Tuner.check(Instrument), printing generic check.
Java only dispatches dynamically on the receiver.

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 check
  • Hop 1 (run time): i.accept(...) is dispatched on the instrument, so we land inside Guitar.accept.
  • Hop 2 (compile time): inside Guitar, this is labeled Guitar, so the compiler picks check(Guitar).
Double dispatch sequence: the caller calls i.accept(tuner); dispatch on the instrument lands in Guitar.accept; Guitar.accept calls tuner.check(this) where this has static type Guitar, so check(Guitar) runs and prints guitar check. Double dispatch sequence: the caller calls i.accept(tuner); dispatch on the instrument lands in Guitar.accept; Guitar.accept calls tuner.check(this) where this has static type Guitar, so check(Guitar) runs and prints guitar check.
Two hops, two decisions: double dispatch.

Two hops, so it’s called double dispatch. It’s the trick behind the Visitor pattern.

The receiver is dynamic. The arguments are static.

When to lean on it, and when not

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.)

Decision flowchart: if new types keep arriving and operations are stable, override methods and rely on dynamic dispatch. If the types are fixed and new operations keep arriving, use a sealed hierarchy with an exhaustive switch. If you need to choose by two runtime types, use double dispatch or the Visitor pattern. Decision flowchart: if new types keep arriving and operations are stable, override methods and rely on dynamic dispatch. If the types are fixed and new operations keep arriving, use a sealed hierarchy with an exhaustive switch. If you need to choose by two runtime types, use double dispatch or the Visitor pattern.

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.

Recap

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.

Recap chain: Instrument i = new Guitar(); the label (static type) is checked by the compiler; the contents (dynamic type) are known at run time; the object points to its class; the class's table gives slot 1; slot 1 is Guitar.play, which prints strum. Recap chain: Instrument i = new Guitar(); the label (static type) is checked by the compiler; the contents (dynamic type) are known at run time; the object points to its class; the class's table gives slot 1; slot 1 is Guitar.play, which prints strum.
  • Dynamic dispatch picks the method by the object’s class, not the variable’s type.
  • The compiler picks the slot; the object picks the table.
  • Fields, static and private methods, constructors and super calls are not dispatched.
  • Overloads are chosen at compile time from the arguments’ labels; Java is single dispatch, and double dispatch (Visitor) adds a second hop.
  • Prefer overriding when types keep arriving; prefer a sealed switch when operations do.

One line of code, many behaviors. The compiler reads the label. The runtime opens the box.