# PolymorphismA new filter plugs right in, and breaks the before-and-after slider. Learn what polymorphism really asks of every implementation: one role, many actors, and the promise behind it.

Your photo editor has a before and after slider. Drag it across, and you see the photo with and
without the filter. A new sharpen filter plugs right in, with no change to the editor. But now both
halves of the slider look sharp. It compiles. It fits the interface. So what did it get wrong? To
answer that, we need **polymorphism**: what it is, its three kinds, and the promise behind it.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="8OgTU0S2E7I" title="Polymorphism" >}}

This lesson is about the *design* idea. How the JVM actually picks the right method at run time
(method tables, overloading vs overriding) has its own lesson: [Dynamic Dispatch](/fundamentals/dynamic-dispatch/).

## Both halves look sharp

The new filter needed no edit to the editor: that's polymorphism working. The slider now lies about
the "before" photo: that's polymorphism failing. Both happened with code that compiles. Keep the
question in mind; the answer comes in [the promise](#play-the-part-keep-the-promise).

## The role and the actors

Think of a role in a play. Hamlet was written about four hundred years ago (Shakespeare, around
1600), and the script still fixes every line and every cue. Thousands of actors have played him,
each in their own way. The play never changed. Only the casting did.

That's polymorphism. The word means "many forms" (*poly* + *morph*; Christopher Strachey brought it
into programming in 1967). In code, it's **one interface for many types**.

| Play | Code |
|---|---|
| the role | an interface (`Filter`) |
| the script | its contract: what every actor must do |
| the actors | the classes that implement it |
| casting | which object you get at run time |

And the play doesn't care who's cast tonight. It calls for Hamlet, and whoever plays him answers.

## The obvious version: ask which filter

Let's go back to before there was any interface. The editor picks a filter by its name.

```java
// Editor
Image applyFilter(String name, Image img) {
    if (name.equals("grayscale")) {
        return toGray(img);
    } else if (name.equals("blur")) {
        return boxBlur(img, 3);
    } else {
        throw new IllegalArgumentException(name);
    }
}
```

If it's grayscale, turn it grey. If it's blur, soften it. Anything else is an error. With two
filters, this is fine: one method, and everything is in sight.

## Why it breaks

Then a third filter arrives. The chain grows a branch, and the editor is edited again. And the same
chain turns up elsewhere: in the thumbnails, and in the menu labels. Each new filter means finding
all of them.

Worse, a plugin can't add a filter at all. It would have to edit your editor, and it can't.

```mermaid {alt="A new vignette filter forces edits in three places: applyFilter in the editor, the thumbnails code and the menu labels code. A plugin jar cannot edit any of them." caption="A chain of type checks makes the editor own every filter."}
flowchart LR
  V["new filter: vignette"] --> E["Editor.applyFilter"]
  V --> T["Thumbnails"]
  V --> M["MenuLabels"]
  P["vignette-plugin.jar"] -. "can't edit" .-> E
  class E,T,M bad
  class P c6
```

In the play, that's a director who rewrites the script for every new actor. The fix has a name:
*Replace Conditional with Polymorphism* (Martin Fowler's refactoring catalog). The code-smell side
of the same story is [Switch Statements](/code-smells/switch-statements/).

## The key insight: write to the role

So flip it. The editor shouldn't know any filter by name. It should ask only for the role.

```java
public interface Filter {
    /** Returns a new image the same size as in. Never changes in. */
    Image apply(Image in);
}
```

The role has one method, `apply`. Its comment is the contract: return a new image the same size,
and never change the one you were given. Now the editor's loop is written once. It runs whatever
filters it's handed, one after another.

```java
// Editor
Image run(List<Filter> chain, Image img) {
    for (Filter f : chain) {
        img = f.apply(img);
    }
    return img;
}
```

The Gang of Four put it as "program to an interface, not an implementation" (*Design Patterns*,
1994). Or, in the play:

> **One role, many actors.**

## Building it: many actors, one loop

Each filter is a class that plays the role. Grayscale turns the image grey. Blur softens it, with
its own radius.

```java
public class Grayscale implements Filter {
    public Image apply(Image in) { return toGray(in); }
}

public class Blur implements Filter {
    private final int radius;
    public Blur(int radius) { this.radius = radius; }
    public Image apply(Image in) { return boxBlur(in, radius); }
}
```

A year later, someone you've never met ships a vignette plugin. It implements the same role, and
the editor runs it.

```java
// vignette-plugin.jar, written a year later
public class Vignette implements Filter {
    public Image apply(Image in) { return darkenEdges(in, 0.4); }
}
```

No edit to the editor, and no recompile. The old code calls code that didn't exist when it was
written. Which filters run is decided at run time, from the menu the user clicks: that's the casting.

A role with one method can even be played by a lambda (`Filter` is a functional interface). Flip is
one line, and no class at all:

```java
Filter flip = in -> in.mirrored();
```

```mermaid {alt="Class diagram: the Filter interface with apply(Image). Grayscale, Blur and Vignette implement it; the Editor depends only on Filter." caption="The editor knows the role, not the actors."}
classDiagram
  class Filter {
    <<interface>>
    +apply(Image in) Image
  }
  class Editor {
    +run(List~Filter~ chain, Image img) Image
  }
  Editor --> Filter : uses
  Filter <|.. Grayscale
  Filter <|.. Blur
  Filter <|.. Vignette
```

How the virtual machine finds the right `apply` at run time is its own story:
[Dynamic Dispatch](/fundamentals/dynamic-dispatch/).

## Three kinds of polymorphism

What we've built is one kind of polymorphism. There are three, and they're easy to mix up.

**Subtype polymorphism.** One call, `apply`, runs a different method for each type behind it.

**Parametric polymorphism** (generics). One piece of code works for any type, because it never looks
inside. `last` returns the last item of any list, a list of filters or a list of names:

```java
static <T> T last(List<T> items) {
    return items.get(items.size() - 1);
}
```

**Ad hoc polymorphism** (overloading). One name, with separate code for each argument type. `open`
takes a path or a web address, and the compiler picks. Like the word *play*: a play, or to play.

```java
Image open(Path file) { ... }
Image open(URL link) { ... }
```

| Kind | In Java | What varies | Chosen |
|---|---|---|---|
| subtype | interfaces, overriding | many codes behind one call | at run time |
| parametric | generics (`List<T>`) | nothing: one code for any type | (one code) |
| ad hoc | overloading | one name, code per argument type | at compile time |

Christopher Strachey named ad hoc and parametric polymorphism in the sixties (*Fundamental Concepts
in Programming Languages*, 1967). Luca Cardelli and Peter Wegner added the subtype kind, which they
called inclusion polymorphism, in 1985.

## Play the part, keep the promise

Now back to the slider. The editor keeps the original photo, applies the filter, and shows both
side by side.

```java
// Editor: the before-and-after slider
Image original = photo;
Image edited = filter.apply(photo);
slider.show(original, edited);
```

Here's sharpen. It changes the image it was given, then hands that same image back.

```java
public class Sharpen implements Filter {
    public Image apply(Image in) {
        sharpenInPlace(in);     // changes the original
        return in;
    }
}
```

So `original` and `edited` are the same object. Sharpen one, and you've sharpened both. That's the
hook's answer.

```mermaid {alt="Sequence: the editor keeps original equal to photo, calls sharpen.apply(photo); Sharpen changes the photo in place and returns the same object, so the slider shows the same sharpened image as before and after." caption="original and edited are the same object."}
sequenceDiagram
  participant E as Editor
  participant S as Sharpen
  participant P as photo
  E->>E: original = photo
  E->>S: apply(photo)
  S->>P: sharpenInPlace(photo)
  S-->>E: returns photo (same object)
  Note over E,P: slider.show(original, edited) shows one sharp image twice
```

The signature fits, so the compiler is happy. But the contract said never change the input.

> **The compiler checks the lines, not the performance.**

It's an understudy who knows every line, but skips the sword fight. The words fit. The scene breaks.

Barbara Liskov put this into words (a 1987 keynote, *Data Abstraction and Hierarchy*; made precise
with Jeannette Wing in 1994). Paraphrased: anything true of the type must stay true of each subtype.
No stronger demands, and no weaker results. It's a rule about behaviour, not just method names.

The fix is three lines. Copy first, sharpen the copy, and return it. Now the before half stays soft.

```java
public class Sharpen implements Filter {
    public Image apply(Image in) {
        Image out = in.copy();
        sharpenInPlace(out);
        return out;
    }
}
```

> **Play the part, keep the promise.**

A subclass that refuses part of its parent's promise is a code smell of its own:
[Refused Bequest](/code-smells/refused-bequest/). And keeping an object's own promise is the
subject of [Encapsulation](/fundamentals/encapsulation/).

## The JDK's own edge: `List.of`

The JDK has a famous case of its own. This method takes any list of strings and adds a default tag.

```java
void addDefaults(List<String> tags) {
    tags.add("draft");
}

addDefaults(new ArrayList<>());    // fine
addDefaults(new LinkedList<>());   // fine
addDefaults(List.of("travel"));    // UnsupportedOperationException
```

Give it an `ArrayList`, fine. A `LinkedList`, fine. A list made with `List.of`, and it throws. Is
that a broken promise? Not quite. The javadoc marks `add` as an *optional operation*, and lists from
`List.of` can't be changed: every mutator throws `UnsupportedOperationException`.

So the promise of a list is weaker than most callers assume. If your code needs to add, say so:
copy into a list you own.

```java
List<String> mine = new ArrayList<>(tags);
mine.add("draft");
```

It's the understudy rule from the other side. When a script says *may*, every caller has to plan
for *may not*.

## Not the same as inheritance

A common belief is that polymorphism means class hierarchies. But look at what we've cast: `flip`
is a lambda, with no class at all. `last` works for any type, with no subclass in sight. `Vignette`
shares no parent with `Blur`.

Inheritance is a way to reuse code (and one way to declare a subtype). Polymorphism is the caller not
caring which form it gets. You can have either one without the other. And dynamic dispatch is the
machinery underneath: it's how subtype polymorphism works, not what it is.

```mermaid {alt="Comparison: inheritance reuses a parent's code and is one way to create a subtype; polymorphism means the caller doesn't care which form it gets, and can come from interfaces, lambdas or generics. Dynamic dispatch is the mechanism under subtype polymorphism." caption="Related, but not the same."}
flowchart LR
  subgraph INH["inheritance"]
    direction TB
    I1["reuse a parent's code"] --> I2["one way to make a subtype"]
  end
  subgraph POL["polymorphism"]
    direction TB
    P1["the caller doesn't care"] --> P2["interfaces, lambdas, generics"]
    P2 --> P3["dynamic dispatch underneath"]
  end
  INH ~~~ POL
  class P1 c1
  class P3 muted
```

## When not to use it

So should every class hide behind an interface? No. A role pays off when actors keep arriving.

- If there's one implementation, and no second in sight, use a plain class. Pull out the interface
  when the second actor shows up.
- If the kinds are fixed, but new operations keep arriving, a sealed type with a complete switch
  fits better. That's the other direction (see [Switch Statements](/code-smells/switch-statements/)).
- And plain data, with no behaviour to vary, is better as a record.

```mermaid {alt="Decision: will a second implementation arrive? No: use a plain class. Yes: are the kinds fixed while new operations keep arriving? Yes: a sealed type with an exhaustive switch. No: write callers against an interface. Plain data with no behavior: a record." caption="A role pays off when actors keep arriving."}
flowchart TD
  Q1{"a second implementation coming?"} -->|no| C["plain class"]
  Q1 -->|yes| Q2{"kinds fixed, operations growing?"}
  Q2 -->|yes| S["sealed type + exhaustive switch"]
  Q2 -->|no| R["write callers to an interface"]
  class R good
  class C,S muted
```

## Recap

- A chain of type checks makes the caller own every form.
- A role lets the caller be written once, and new forms plug in later, even from strangers.
- There are three kinds: subtype, parametric and ad hoc.
- Fitting the signature isn't the same as keeping the promise; read the contract.

```mermaid {alt="Recap chain: define the role and its contract, write the caller once, cast any actor, check each actor keeps the promise." caption="One role, many actors. Play the part, keep the promise."}
flowchart LR
  A["role + contract"] --> B["caller written once"] --> C["cast any actor"] --> D["keeps the promise?"]
  class A c1
  class D good
```

Checklist:

- Does the caller check a type or name before acting? Could it ask a role instead?
- Does the role's contract say what callers may rely on (inputs, outputs, side effects)?
- Does every implementation keep it, including ones written by other teams?
- Does the code depend on an "optional operation" it doesn't check for?
- Is there really a second implementation, or would a plain class do?

> **One role, many actors. Play the part, keep the promise.**

Related lessons: [Dynamic Dispatch](/fundamentals/dynamic-dispatch/),
[Encapsulation](/fundamentals/encapsulation/), [Strategy Pattern](/patterns/strategy-pattern/),
[Factory Method](/patterns/factory-method-pattern/).

## Further reading

- Luca Cardelli and Peter Wegner, "On Understanding Types, Data Abstraction, and Polymorphism",
  *ACM Computing Surveys* 17(4), 1985.
- Barbara Liskov and Jeannette Wing, "A Behavioral Notion of Subtyping", *ACM TOPLAS*, 1994; see also
  [Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle).
- Refactoring catalog: [Replace Conditional with Polymorphism](https://refactoring.com/catalog/replaceConditionalWithPolymorphism.html).
- [`java.util.List`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/List.html)
  javadoc: optional operations and unmodifiable lists.
