November 25, 20269 minutes
A 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.
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.
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.
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.
Let’s go back to before there was any interface. The editor picks a filter by its name.
// 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.
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.
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.
So flip it. The editor shouldn’t know any filter by name. It should ask only for the role.
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.
// 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.
Each filter is a class that plays the role. Grayscale turns the image grey. Blur softens it, with its own radius.
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.
// 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:
Filter flip = in -> in.mirrored();How the virtual machine finds the right apply at run time is its own story:
Dynamic Dispatch.
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:
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.
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.
Now back to the slider. The editor keeps the original photo, applies the filter, and shows both side by side.
// 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.
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.
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.
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. And keeping an object’s own promise is the subject of Encapsulation.
List.ofThe JDK has a famous case of its own. This method takes any list of strings and adds a default tag.
void addDefaults(List<String> tags) {
tags.add("draft");
}
addDefaults(new ArrayList<>()); // fine
addDefaults(new LinkedList<>()); // fine
addDefaults(List.of("travel")); // UnsupportedOperationExceptionGive 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.
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.
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.
So should every class hide behind an interface? No. A role pays off when actors keep arriving.
Checklist:
One role, many actors. Play the part, keep the promise.
Related lessons: Dynamic Dispatch, Encapsulation, Strategy Pattern, Factory Method.
java.util.List
javadoc: optional operations and unmodifiable lists.