# Dynamic DispatchOne 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.

{{< lesson-video youtube="pPyZ9P4_tlI" title="Dynamic Dispatch" >}}

## One line, three behaviors

Here's our band, written in Java:

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

```java
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.

```mermaid {alt="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." caption="One call site, compiled once, three methods at run time."}
flowchart TD
  C(["i.play()<br/>one call site, one instruction"]) --> Q{"Which class is<br/>the object?"}
  Q -->|Guitar| G["Guitar.play()<br/>strum!"]
  Q -->|Drum| D["Drum.play()<br/>boom!"]
  Q -->|Piano| P["Piano.play()<br/>plink!"]
  class C hl
  class G guitar
  class D drum
  class P piano
```

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:

```java
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 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()`.

```mermaid {alt="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." caption="The compiler reads the label. The runtime opens the box."}
flowchart LR
  subgraph CT["Compile time: read the label"]
    direction TB
    L["label: Instrument"] --> OK["i.play(): compiles"]
    L --> NO["i.strum(): compile error"]
  end
  subgraph RT["Run time: open the box"]
    direction TB
    B["contents: a Guitar"] --> R["runs Guitar.play()<br/>strum!"]
  end
  CT ~~~ RT
  class L,OK compile
  class NO bad
  class B runtime
  class R guitar
```

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

```java
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:

```java
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.

```mermaid {alt="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." caption="One new type, edits everywhere."}
flowchart LR
  V["new class Violin"] --> A["perform()<br/>+ instanceof Violin"]
  V --> B["tuneAll()<br/>+ instanceof Violin"]
  V --> C["price()<br/>+ instanceof Violin"]
  V --> D["pack()<br/>branch forgotten"]
  D --> S["violin silently<br/>does nothing"]
  class V violin
  class A,B,C bad
  class D,S muted
```

Everything the program knows about violins ends up scattered across every method. (This is the
[Switch Statements code smell](https://refactoring.guru/smells/switch-statements) 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:

```java
void perform(Instrument i) {
    i.play();
}
```

The band leader just counts in, *one, two, three, four*, and every musician already knows
their part.

```mermaid {alt="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." caption="Ask, then branch (top) versus tell, and let the class answer (bottom)."}
flowchart TB
  subgraph ASK["Ask: instanceof chain"]
    direction TB
    P1["perform(i)"] --> Q1{"what are you?"}
    Q1 --> G1["g.strum()"]
    Q1 --> D1["d.hit()"]
    Q1 --> PI1["p.press()"]
  end
  subgraph TELL["Tell: dynamic dispatch"]
    direction TB
    P2["perform(i)"] --> C2["i.play()"]
    C2 -.-> G2["Guitar.play()"]
    C2 -.-> D2["Drum.play()"]
    C2 -.-> PI2["Piano.play()"]
  end
  ASK ~~~ TELL
  class Q1 bad
  class C2 hl
  class G1,G2 guitar
  class D1,D2 drum
  class PI1,PI2 piano
```

```mermaid {alt="Class diagram: abstract class Instrument with tune and abstract play. Guitar, Drum and Piano extend it and override play; Piano also overrides tune."}
classDiagram
  class Instrument {
    <<abstract>>
    +tune()
    +play()
  }
  class Guitar { +play() }
  class Drum { +play() }
  class Piano {
    +play()
    +tune()
  }
  Instrument <|-- Guitar
  Instrument <|-- Drum
  Instrument <|-- Piano
```

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

```text
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:

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

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.

```mermaid {alt="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." caption="The compiler picks the slot; the object picks the table."}
flowchart TD
  I["variable i<br/>label: Instrument"] -->|1 follow i| O["a Guitar object"]
  O -->|2 class pointer| T["Guitar's table"]
  T -->|3 slot 1| S["Guitar.play()"]
  S -->|4 jump| OUT(["strum!"])
  class I compile
  class O runtime
  class T,S guitar
  class OUT hl
```

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:

```java
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`:

```java
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:

```mermaid {alt="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." caption="JDK code (java.base) calling your override."}
sequenceDiagram
  participant You as your code
  participant PS as println(Object x)
  participant SV as String.valueOf(x)
  participant G as Guitar.toString()
  You->>PS: println(new Guitar())
  PS->>SV: valueOf(x)
  SV->>G: x.toString()
  Note over SV,G: dynamic dispatch on x
  G-->>SV: "Guitar"
  SV-->>PS: "Guitar"
```

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](/patterns/state-pattern/) 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:

```java
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.

```mermaid {alt="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." caption="Label or contents?"}
flowchart TD
  M["i.something"] --> Q{"Overridable<br/>instance method?"}
  Q -->|yes| RT["Opens the box<br/>chosen at run time<br/>from the object's class"]
  Q -->|no| CT["Reads the label<br/>chosen at compile time"]
  CT --> L["fields · static methods<br/>private methods · constructors<br/>super.method() calls"]
  class RT runtime
  class CT,L compile
```

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

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

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

```mermaid {alt="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." caption="Java only dispatches dynamically on the receiver."}
flowchart LR
  subgraph CT["Compile time: arguments' labels"]
    direction TB
    A["argument i<br/>label: Instrument"] --> SIG["signature fixed:<br/>check(Instrument)"]
  end
  subgraph RT["Run time: receiver only"]
    direction TB
    R["receiver: a Tuner"] --> IMPL["Tuner.check(Instrument)<br/>generic check"]
  end
  CT ~~~ RT
  class A,SIG compile
  class R,IMPL runtime
```

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:

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

```mermaid {alt="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." caption="Two hops, two decisions: double dispatch."}
sequenceDiagram
  participant C as caller
  participant G as Guitar.accept(t)
  participant T as Tuner
  C->>G: i.accept(tuner)
  Note over C,G: hop 1: run time, the receiver is a Guitar
  G->>T: t.check(this)
  Note over G,T: hop 2: compile time, this is labeled Guitar
  T-->>C: check(Guitar) prints "guitar check"
```

Two hops, so it's called **double dispatch**. It's the trick behind the [Visitor pattern](/patterns/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:

```java
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*.)

```mermaid {alt="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."}
flowchart TD
  S{"What keeps changing?"} -->|new types| O["Override methods<br/>(dynamic dispatch)"]
  S -->|new operations,<br/>types fixed| W["sealed class +<br/>exhaustive switch"]
  S -->|behavior depends on<br/>two runtime types| V["double dispatch<br/>(Visitor)"]
  class O runtime
  class W compile
  class V hl
```

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

```mermaid {alt="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."}
flowchart TD
  A["Instrument i = new Guitar();"] --> B["label = static type<br/>compiler checks what you may call"]
  B --> C["contents = dynamic type<br/>known at run time"]
  C --> D["object → its class → table"]
  D --> E["slot 1 → Guitar.play()<br/>strum!"]
  class B compile
  class C runtime
  class D hl
  class E guitar
```

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