Polymorphism

One call, many behaviors: code written against a common type runs the right method for each object at run time. It is how designs grow without a switch statement in the middle.

Overview

Polymorphism means that one piece of code can work with values of many types. In object-oriented design the form that matters is subtype polymorphism: you write shape.area() once, against the Shape type, and the runtime runs Circle.area or Rectangle.area depending on which object is really there. The caller never asks what kind of shape it has.

That is the mechanism behind almost every design pattern and behind the Open/Closed Principle: to add a new shape you add a new class, and no existing code changes. Interviewers listen for whether you reach for it instead of a chain of type checks, and whether you can say what happens underneath when the call is made.

One call, many behaviors

Here is the smallest useful case: a report that adds up areas without knowing which shapes it was given.

The same design in Python follows.

Interview questions

  • What is the difference between compile-time and run-time polymorphism?
  • How would you refactor a switch on a type field into polymorphism?
  • How does dynamic dispatch work under the hood?
  • Can you have polymorphism without inheritance?
  • When is a switch better than polymorphism?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio