AlgoViz

Polymorphism

medium 45 min

One 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

0:00 / 4:47

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

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

  2. 1967

    Simula 67 has classes, subclasses and virtual procedures: a call runs the version of the object's own class.

  3. 1985

    Luca Cardelli and Peter Wegner publish On Understanding Types, Data Abstraction, and Polymorphism. They add inclusion polymorphism, which today we call subtype polymorphism.

  4. 1986

    Dan Ingalls describes double dispatch in Smalltalk: how to choose a method by the types of two objects.

  5. 1987

    Barbara Liskov's keynote Data Abstraction and Hierarchy states when one type may stand in for another.

  6. 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 Protocol work 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.

Sam's wind-up bench

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.

Python
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 right
Two functions, the same question twice. One of them was forgotten when podcasts came.
Edit and run it in your browser

The bad shape: everybody knows every kind

«enum»KindSONGPODCASTRADIOItem+ kind: Kind+ title: str+ artist: str?+ episode: int?+ station: str?

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 same list of cases in several classes is the clearest sign that a type is missing.

The good shape: each kind answers for itself

Player+ play(p: Playable)Statistics+ total(list): int«interface»Playable+ label(): str+ minutes(): int?

1/3Two questions

The callers need a label and a number of minutes. That is the contract.

usesimplements

The question mark on minutes is part of the contract: live radio has no length, and the caller must expect that.

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

Python and JavaScript skip the first half: they look at the object only, and a missing method is a run-time error.
Python
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)
The orchestra: one loop, four animals, and a robot that nobody planned.
Edit and run it in your browser

One loop, different players

The conductor sends the same message each time. How the run-time finds the method (method tables and caches) is on Polymorphism under the hood.

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

OverridingOverloading
ChosenAt run timeBefore running, by the compiler
Chosen byThe object that receives the callThe declared types of the arguments
Also calledLate binding, dynamic dispatchEarly binding, static polymorphism
SignatureThe sameMust differ in number, type or order
Return typeThe same or a subtype (covariant)May differ, but alone it is not enough
AccessNot narrower than in the parentFree
Needs inheritanceYes, or an interfaceNo, although inherited methods count too
Not possible forfinal, static and private methods (Java)Python and JavaScript functions: the last definition wins
The rules of overriding, with every edge case, are on Method overriding.
Java
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 double
Overloading: three methods with one name. The compiler picks, so a wrong pick is already in the compiled program.

Signs 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 if is clearer
  • The caller still asks isinstance after the call

Languages

The same idea in five dialects

LanguageContractDispatch by defaultOverloading
Javainterface, abstract classDynamic for instance methodsYes
C++Abstract class with pure virtual methodsStatic, dynamic only with virtual through a pointer or referenceYes
PythonAny object with the method, ABC, ProtocolDynamicNo. functools.singledispatch dispatches on the first argument
TypeScriptinterface, by shapeDynamic (it is JavaScript)Several signatures, one body
Gointerface, satisfied without a declarationDynamic through an interface valueNo

Judgement

Methods on kinds, or a switch on kinds?

Which tool for many kinds?

Polymorphism inside the patterns

PatternThe polymorphic call
StrategyThe context asks its current algorithm
StateThe context asks its current state
Template methodA fixed recipe calls an overridden step
VisitorTwo calls: the element's, then the visitor's
CompositeA folder and a file answer the same question
FactoryCreation 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.

Sources