Polymorphism
medium 45 minOne call, many behaviours: the caller asks for the same thing, and the object that receives the call decides how it is done.
Video lesson · Chapter 1 of 6
Make a prediction
Polymorphism
1:02Reel
Theory
Read or listen first. About 3 min.
What it is
Polymorphism means many forms, from the Greek *poly* (many) and *morphe* (form). In a program it means that one name, one call or one piece of code works with values of different types.
In object design the word usually means subtype polymorphism: a variable has a general type, the object in it has a special one, and a method call runs the version that belongs to the object. Animal a = new Dog() and then a.makeSound() prints Woof.
There are three more kinds. Overloading picks among methods with one name by the argument types, before the program runs. Generics run the same code for any type. Coercion converts a value, as in 1 + 2.5.
Why it exists
Without it, every caller must ask: what kind are you? The answer is a chain of if or a switch, and the same chain is needed in every place that treats the kinds differently. A new kind means finding all of them.
With it, each kind carries its own behaviour. The caller is written once and works with kinds that do not exist yet. A list can hold dogs, cats and robots, and one loop serves all of them.
It also makes testing easy. A caller that only knows a contract accepts a small fake object as happily as the real one.
A short history
1967
Christopher Strachey, in lecture notes called Fundamental Concepts in Programming Languages, separates ad hoc polymorphism (a different function per type) from parametric polymorphism (one function for all types).
1967
Simula 67 has classes, subclasses and virtual procedures: a call runs the version of the object's own class.
1985
Luca Cardelli and Peter Wegner publish On Understanding Types, Data Abstraction, and Polymorphism. They add inclusion polymorphism, which today we call subtype polymorphism.
1986
Dan Ingalls describes double dispatch in Smalltalk: how to choose a method by the types of two objects.
1987
Barbara Liskov's keynote Data Abstraction and Hierarchy states when one type may stand in for another.
2023
Java 21 finishes pattern matching for
switch(JEP 441). With sealed types the compiler checks that every kind is handled: the opposite tool, for closed sets of kinds.
Words to know
- Static type
- The type the compiler knows for a variable. It decides which calls are allowed.
- Dynamic type
- The class of the object that is really there. It decides which version runs.
- Overriding
- A subclass gives its own body for an inherited method with the same signature.
- Overloading
- Several methods with one name and different parameters.
- Dynamic dispatch
- Finding the method at run time from the object's class. Also called late binding.
- Early binding
- The choice is made before the program runs. Overloads, static methods and private methods are bound early.
- Duck typing
- An object is accepted because it has the method, whatever its class is.
- Structural typing
- Duck typing checked by a tool: the shape counts, not the declared parent. TypeScript, Go and Python's
Protocolwork this way. - Double dispatch
- Choosing by the types of two objects, with two calls in a row.
- Substitutability
- Any object of a subtype may be used where the general type is expected, without surprises.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Understand it
Start here
One key, many toys
Sam has a bench of wind-up toys. Watch who knows how a toy moves: the person with the key, or the toy.
Frames 1 and 2 are a type switch, 3 to 5 are subtype polymorphism, 6 is duck typing, 7 is why a contract is more than a method name.
The smell
The question that is asked everywhere
A music player has songs, podcasts and live radio. The first version keeps a kind in each item.
def label(item): if item["kind"] == "song": return f'{item["title"]} - {item["artist"]}' elif item["kind"] == "podcast": return f'{item["title"]}, episode {item["episode"]}' raise ValueError(item["kind"])def minutes(item): if item["kind"] == "song": return item["seconds"] // 60 return 0 # podcasts fall in herepod = {"kind": "podcast", "title": "Bread", "episode": 4, "seconds": 2400}print(label(pod)) # Bread, episode 4print(minutes(pod)) # 0, and 40 would be rightThe bad shape: everybody knows every kind
1/3An item with a kind
One class for all kinds. Most fields are empty for most items, and nothing says which belong together.
uses
The good shape: each kind answers for itself
1/3Two questions
The callers need a label and a number of minutes. That is the contract.
usesimplements
How it works
Two types, two moments
Every variable has two types. The static type is what the code says. The dynamic type is what the object is. They answer two different questions at two different moments.
What happens to a.makeSound()
from abc import ABC, abstractmethodclass Animal(ABC): @abstractmethod def make_sound(self) -> str: ... def sleep(self) -> str: return "Zzz..."class Dog(Animal): def make_sound(self) -> str: return "Woof!"class Cat(Animal): def make_sound(self) -> str: return "Meow!"class Cow(Animal): def make_sound(self) -> str: return "Moo!"class Bird(Animal): def make_sound(self) -> str: return "Tweet!"def perform(orchestra) -> list[str]: return [player.make_sound() for player in orchestra]orchestra = [Dog(), Cat(), Cow(), Bird()]print(perform(orchestra)) # ['Woof!', 'Meow!', 'Moo!', 'Tweet!']print(orchestra[0].sleep()) # Zzz... (inherited, the same for all)class Robot: # not an Animal, but it has the method def make_sound(self) -> str: return "Beep!"print(perform(orchestra + [Robot()]))try: Animal() # an abstract class makes no objectsexcept TypeError as error: print("refused:", error)One loop, different players
Kinds
Four kinds of polymorphism
Subtype
One call, the object's class decides. Chosen at run time. Interfaces, abstract classes, overriding.
Ad hoc
One name, several functions. Chosen by the argument types. Overloading and operators such as
+.Parametric
One function for all types, the same code each time:
first(list). See Generics.Coercion
The value is converted to fit, as in
1 + 2.5. Handy, and a source of surprises.
Overriding and overloading
| Overriding | Overloading | |
|---|---|---|
| Chosen | At run time | Before running, by the compiler |
| Chosen by | The object that receives the call | The declared types of the arguments |
| Also called | Late binding, dynamic dispatch | Early binding, static polymorphism |
| Signature | The same | Must differ in number, type or order |
| Return type | The same or a subtype (covariant) | May differ, but alone it is not enough |
| Access | Not narrower than in the parent | Free |
| Needs inheritance | Yes, or an interface | No, although inherited methods count too |
| Not possible for | final, static and private methods (Java) | Python and JavaScript functions: the last definition wins |
class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; }}Calculator calc = new Calculator();calc.add(5, 10); // 15, add(int, int)calc.add(1.5, 2.5); // 4.0, add(double, double)calc.add(1, 2, 3); // 6, add(int, int, int)calc.add(5, 2.5); // 7.5, the 5 is widened to doubleSigns of a good use
- Callers need the same answer from different kinds
- New kinds arrive more often than new questions
- Tests want to replace a part
- The contract fits in one or two sentences
Signs of a forced use
- Subclasses differ in a number only: use a field
- Half of the methods raise
not supported - One caller, two kinds, no growth: an
ifis clearer - The caller still asks
isinstanceafter the call
Languages
The same idea in five dialects
| Language | Contract | Dispatch by default | Overloading |
|---|---|---|---|
| Java | interface, abstract class | Dynamic for instance methods | Yes |
| C++ | Abstract class with pure virtual methods | Static, dynamic only with virtual through a pointer or reference | Yes |
| Python | Any object with the method, ABC, Protocol | Dynamic | No. functools.singledispatch dispatches on the first argument |
| TypeScript | interface, by shape | Dynamic (it is JavaScript) | Several signatures, one body |
| Go | interface, satisfied without a declaration | Dynamic through an interface value | No |
Judgement
Methods on kinds, or a switch on kinds?
Which tool for many kinds?
Polymorphism inside the patterns
| Pattern | The polymorphic call |
|---|---|
| Strategy | The context asks its current algorithm |
| State | The context asks its current state |
| Template method | A fixed recipe calls an overridden step |
| Visitor | Two calls: the element's, then the visitor's |
| Composite | A folder and a file answer the same question |
| Factory | Creation is the one place that still names the kinds |
Summary
The whole topic in one minute.
The caller knows the contract, the object knows the behaviour. Static type decides what you may call, dynamic type decides what runs.
Overriding is chosen at run time by the receiver. Overloading is chosen before that by the declared types of the arguments. Most puzzles in interviews mix these two.
Use it when the kinds grow and the operations are few. For a closed set of kinds with many operations, an exhaustive switch or a visitor is better.
- One call, many behaviours: the receiver decides.
- Static type: what may be called. Dynamic type: what runs.
- Overriding is late and looks at the object. Overloading is early and looks at declared argument types.
- A contract is a method and its promises.
- Repeated switches on one kind ask for a type.
- Kinds grow: methods. Operations grow: switch or visitor.