Skip to main content

Polymorphism — Compile-Time vs Runtime

Editorial

Introduction

Inheritance — Code Reuse & Hierarchies built an Employee family, and its loop called display_info() on a manager, a developer and an intern. Each printed something different from the same call. That was polymorphism, before we gave it a name.

The word comes from Greek and means "many forms". The Java tutorial explains where programmers borrowed it from: "The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages." In code it means that one call can run different code, depending on the object it is made on or on the arguments it is given.

There are two kinds, and they differ in when the choice is made:

  • Runtime polymorphism is chosen while the program runs, by the object itself. It comes from overriding: a child class writes its own version of a parent's method.
  • Compile-time polymorphism is chosen when the code is compiled, by the types of the arguments. It comes from overloading: several methods share a name and differ in their parameters.

Runtime polymorphism matters most for design. It lets code work with a general type while each specific type brings its own behaviour, and many of the patterns in Design Patterns - Low Level Design are built on it.

Runtime Polymorphism: the Object Decides

Runtime polymorphism means that a variable declared with a general type can hold an object of a more specific type, and a call through that variable runs the specific type's own method. The Java tutorial puts it this way: "The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type."

Here is a set of shapes. Shape says that every shape has an area() and a describe(), and each kind of shape writes its own:

import math
from abc import ABC, abstractmethod


class Shape(ABC):
    """What every shape can do; each kind of shape decides how."""

    @abstractmethod
    def area(self) -> float: ...

    @abstractmethod
    def describe(self) -> str: ...


class Circle(Shape):
    def __init__(self, radius: float) -> None:
        self.radius = radius

    def area(self) -> float:
        return math.pi * self.radius ** 2

    def describe(self) -> str:
        return f"Circle(r={self.radius:.1f})"


class Rectangle(Shape):
    def __init__(self, width: float, height: float) -> None:
        self.width = width
        self.height = height

    def area(self) -> float:
        return self.width * self.height

    def describe(self) -> str:
        return f"Rectangle({self.width:.1f} x {self.height:.1f})"


class Triangle(Shape):
    def __init__(self, base: float, height: float) -> None:
        self.base = base
        self.height = height

    def area(self) -> float:
        return 0.5 * self.base * self.height

    def describe(self) -> str:
        return f"Triangle(b={self.base:.1f}, h={self.height:.1f})"


# Works with any shape: it never asks which kind it was given
def print_total_area(shapes: list[Shape]) -> None:
    total = 0.0
    for shape in shapes:
        # Which area() runs is decided by the object itself, when the program runs
        a = shape.area()
        print(f"  {shape.describe()}: area = {a:.2f}")
        total += a
    print(f"  Total area: {total:.2f}")


shapes: list[Shape] = [
    Circle(5.0),
    Rectangle(4.0, 6.0),
    Triangle(3.0, 8.0),
    Circle(2.0),
]
print_total_area(shapes)
import java.util.List;
import java.util.Locale;

// What every shape can do; each kind of shape decides how
abstract class Shape {
    public abstract double area();

    public abstract String describe();
}

class Circle extends Shape {
    private final double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }

    @Override
    public String describe() {
        return String.format(Locale.ROOT, "Circle(r=%.1f)", radius);
    }
}

class Rectangle extends Shape {
    private final double width;
    private final double height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }

    @Override
    public String describe() {
        return String.format(Locale.ROOT, "Rectangle(%.1f x %.1f)", width, height);
    }
}

class Triangle extends Shape {
    private final double base;
    private final double height;

    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    @Override
    public double area() {
        return 0.5 * base * height;
    }

    @Override
    public String describe() {
        return String.format(Locale.ROOT, "Triangle(b=%.1f, h=%.1f)", base, height);
    }
}

public class ShapeDemo {
    // Works with any shape: it never asks which kind it was given
    static void printTotalArea(List<Shape> shapes) {
        double total = 0.0;
        for (Shape shape : shapes) {
            // Which area() runs is decided by the object itself, when the program runs
            double a = shape.area();
            String what = shape.describe();
            System.out.printf(Locale.ROOT, "  %s: area = %.2f%n", what, a);
            total += a;
        }
        System.out.printf(Locale.ROOT, "  Total area: %.2f%n", total);
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(
                new Circle(5.0),
                new Rectangle(4.0, 6.0),
                new Triangle(3.0, 8.0),
                new Circle(2.0));
        printTotalArea(shapes);
    }
}
#include <cstdio>
#include <memory>
#include <string>
#include <vector>

// Pi to double precision: C++17 has no standard constant for it
// (C++20 adds std::numbers::pi)
constexpr double kPi = 3.14159265358979323846;

// What every shape can do; each kind of shape decides how
class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
    virtual std::string describe() const = 0;
};

class Circle : public Shape {
public:
    explicit Circle(double radius) : radius(radius) {}

    double area() const override { return kPi * radius * radius; }

    std::string describe() const override {
        char text[64];
        std::snprintf(text, sizeof text, "Circle(r=%.1f)", radius);
        return text;
    }

private:
    double radius;
};

class Rectangle : public Shape {
public:
    Rectangle(double width, double height) : width(width), height(height) {}

    double area() const override { return width * height; }

    std::string describe() const override {
        char text[64];
        std::snprintf(text, sizeof text, "Rectangle(%.1f x %.1f)", width, height);
        return text;
    }

private:
    double width;
    double height;
};

class Triangle : public Shape {
public:
    Triangle(double base, double height) : base(base), height(height) {}

    double area() const override { return 0.5 * base * height; }

    std::string describe() const override {
        char text[64];
        std::snprintf(text, sizeof text, "Triangle(b=%.1f, h=%.1f)", base, height);
        return text;
    }

private:
    double base;
    double height;
};

// Works with any shape: it never asks which kind it was given
void printTotalArea(const std::vector<std::unique_ptr<Shape>>& shapes) {
    double total = 0.0;
    for (const auto& shape : shapes) {
        // Which area() runs is decided by the object itself, when the program runs
        double a = shape->area();
        std::printf("  %s: area = %.2f\n", shape->describe().c_str(), a);
        total += a;
    }
    std::printf("  Total area: %.2f\n", total);
}

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(5.0));
    shapes.push_back(std::make_unique<Rectangle>(4.0, 6.0));
    shapes.push_back(std::make_unique<Triangle>(3.0, 8.0));
    shapes.push_back(std::make_unique<Circle>(2.0));
    printTotalArea(shapes);
    return 0;
}
// What every shape can do; each kind of shape decides how
abstract class Shape {
  abstract area(): number;
  abstract describe(): string;
}

class Circle extends Shape {
  constructor(private readonly radius: number) {
    super();
  }

  area(): number {
    return Math.PI * this.radius * this.radius;
  }

  describe(): string {
    return `Circle(r=${this.radius.toFixed(1)})`;
  }
}

class Rectangle extends Shape {
  constructor(
    private readonly width: number,
    private readonly height: number,
  ) {
    super();
  }

  area(): number {
    return this.width * this.height;
  }

  describe(): string {
    return `Rectangle(${this.width.toFixed(1)} x ${this.height.toFixed(1)})`;
  }
}

class Triangle extends Shape {
  constructor(
    private readonly base: number,
    private readonly height: number,
  ) {
    super();
  }

  area(): number {
    return 0.5 * this.base * this.height;
  }

  describe(): string {
    return `Triangle(b=${this.base.toFixed(1)}, h=${this.height.toFixed(1)})`;
  }
}

// Works with any shape: it never asks which kind it was given
function printTotalArea(shapes: Shape[]): void {
  let total = 0;
  for (const shape of shapes) {
    // Which area() runs is decided by the object itself, when the program runs
    const a = shape.area();
    console.log(`  ${shape.describe()}: area = ${a.toFixed(2)}`);
    total += a;
  }
  console.log(`  Total area: ${total.toFixed(2)}`);
}

const shapes: Shape[] = [
  new Circle(5.0),
  new Rectangle(4.0, 6.0),
  new Triangle(3.0, 8.0),
  new Circle(2.0),
];
printTotalArea(shapes);
using System;
using System.Collections.Generic;
using System.Globalization;

// What every shape can do; each kind of shape decides how
public abstract class Shape
{
    public abstract double Area();

    public abstract string Describe();

    protected static string F1(double x) =>
        x.ToString("F1", CultureInfo.InvariantCulture);
}

public class Circle : Shape
{
    private readonly double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public override double Area()
    {
        return Math.PI * radius * radius;
    }

    public override string Describe()
    {
        return $"Circle(r={F1(radius)})";
    }
}

public class Rectangle : Shape
{
    private readonly double width;
    private readonly double height;

    public Rectangle(double width, double height)
    {
        this.width = width;
        this.height = height;
    }

    public override double Area()
    {
        return width * height;
    }

    public override string Describe()
    {
        return $"Rectangle({F1(width)} x {F1(height)})";
    }
}

public class Triangle : Shape
{
    private readonly double baseLength;
    private readonly double height;

    public Triangle(double baseLength, double height)
    {
        this.baseLength = baseLength;
        this.height = height;
    }

    public override double Area()
    {
        return 0.5 * baseLength * height;
    }

    public override string Describe()
    {
        return $"Triangle(b={F1(baseLength)}, h={F1(height)})";
    }
}

public static class ShapeDemo
{
    // Works with any shape: it never asks which kind it was given
    static void PrintTotalArea(List<Shape> shapes)
    {
        double total = 0.0;
        foreach (Shape shape in shapes)
        {
            // Which Area() runs is decided by the object itself, when the program runs
            double a = shape.Area();
            string area = a.ToString("F2", CultureInfo.InvariantCulture);
            Console.WriteLine($"  {shape.Describe()}: area = {area}");
            total += a;
        }
        string sum = total.ToString("F2", CultureInfo.InvariantCulture);
        Console.WriteLine($"  Total area: {sum}");
    }

    public static void Main()
    {
        var shapes = new List<Shape>
        {
            new Circle(5.0),
            new Rectangle(4.0, 6.0),
            new Triangle(3.0, 8.0),
            new Circle(2.0),
        };
        PrintTotalArea(shapes);
    }
}
package main

import (
	"fmt"
	"math"
)

// Shape is what every shape can do; each kind of shape decides how. Go has no abstract
// classes: an interface names the methods, and any type that has them is a Shape.
type Shape interface {
	Area() float64
	Describe() string
}

type Circle struct {
	radius float64
}

func (c Circle) Area() float64 {
	return math.Pi * c.radius * c.radius
}

func (c Circle) Describe() string {
	return fmt.Sprintf("Circle(r=%.1f)", c.radius)
}

type Rectangle struct {
	width, height float64
}

func (r Rectangle) Area() float64 {
	return r.width * r.height
}

func (r Rectangle) Describe() string {
	return fmt.Sprintf("Rectangle(%.1f x %.1f)", r.width, r.height)
}

type Triangle struct {
	base, height float64
}

func (t Triangle) Area() float64 {
	return 0.5 * t.base * t.height
}

func (t Triangle) Describe() string {
	return fmt.Sprintf("Triangle(b=%.1f, h=%.1f)", t.base, t.height)
}

// printTotalArea works with any shape: it never asks which kind it was given
func printTotalArea(shapes []Shape) {
	total := 0.0
	for _, shape := range shapes {
		// Which Area() runs is decided by the value itself, when the program runs
		a := shape.Area()
		fmt.Printf("  %s: area = %.2f\n", shape.Describe(), a)
		total += a
	}
	fmt.Printf("  Total area: %.2f\n", total)
}

func main() {
	shapes := []Shape{
		Circle{radius: 5.0},
		Rectangle{width: 4.0, height: 6.0},
		Triangle{base: 3.0, height: 8.0},
		Circle{radius: 2.0},
	}
	printTotalArea(shapes)
}

It prints:

  Circle(r=5.0): area = 78.54
  Rectangle(4.0 x 6.0): area = 24.00
  Triangle(b=3.0, h=8.0): area = 12.00
  Circle(r=2.0): area = 12.57
  Total area: 127.11

The line that matters is a = shape.area(). Inside print_total_area, shape is known only as a Shape. While the program runs, it is a Circle one time and a Triangle the next, and each time the right area() runs. This is called dynamic dispatch: the method is chosen at run time, from the object. The Java tutorial's name for it is "virtual method invocation".

The picture sets both kinds of polymorphism side by side, with what happens when a new shape arrives.

One call, many forms: one call runs different code, picked by the object or by the arguments. At run time, overriding: print_total_area calls shape.area() once for each shape, and each object picks its own area(), which is dynamic dispatch. Circle with r 5.0 runs Circle.area(), pi times r squared, 78.54; Rectangle 4.0 by 6.0 runs Rectangle.area(), w times h, 24.00; Triangle with b 3.0 and h 8.0 runs Triangle.area(), half of b times h, 12.00; Circle with r 2.0 runs Circle.area(), 12.57; the total is 127.11, decided while the program runs. At compile time, overloading: the same method name with different parameter lists, and the compiler picks the version by the arguments. calc.add(3, 5) goes to add(int, int) and gives 8; calc.add(1, 2, 3) goes to add(int, int, int) and gives 6; calc.add with two strings goes to add(String, String) and gives Hello World. The compiler picks by the arguments in Java, C++ and C#; Python and Go have no overloading. Below, a new kind of shape. Checking types with isinstance, one branch for each kind, is closed to new shapes: a Pentagon is skipped with no error, every new shape needs a new branch, and the total is 127.11. Calling shape.area() is open to new shapes: Pentagon(s=2.0) brings its own area() and adds 6.88, the caller never changes, and the total is 133.99.

Compile-Time Polymorphism: Method Overloading

Compile-time polymorphism, also called static polymorphism, means writing several methods with the same name and different parameter lists. The Java tutorial says: "The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures." For each call, the compiler looks at the arguments and picks the matching version before the program runs.

Not every language has it. Java, C++ and C# overload methods this way. Python does not: a second method with the same name replaces the first, and a test showed Calculator().add(3, 5) failing with TypeError: Calculator.add() missing 1 required positional argument: 'c' once a three-number add was written below the two-number one. TypeScript writes several signatures over one body, and Go has no overloading at all. So each listing below says in a comment how its language gets the same effect: Python picks a version by the type of its first argument, when the program runs, through singledispatchmethod from the functools module; TypeScript checks the arguments inside its one body; Go gives each version a name of its own.

from functools import singledispatchmethod


class Calculator:
    # Python has no overloading: singledispatchmethod picks a version by the type of
    # the first argument, when the program runs
    @singledispatchmethod
    def add(self, a, b):
        raise NotImplementedError(f"no add for {type(a).__name__}")

    # Whole numbers: two, or three when a third is given
    @add.register
    def _(self, a: int, b: int, c: int | None = None) -> int:
        if c is None:
            print(f"add for two numbers: {a + b}")
            return a + b
        print(f"add for three numbers: {a + b + c}")
        return a + b + c

    # Two strings
    @add.register
    def _(self, a: str, b: str) -> str:
        print(f"add for two strings: {a + b}")
        return a + b


calc = Calculator()
calc.add(3, 5)
calc.add(1, 2, 3)
calc.add("Hello ", "World")
// The same method name with different parameter lists: method overloading
public class Calculator {
    // Two whole numbers
    public int add(int a, int b) {
        System.out.println("add for two numbers: " + (a + b));
        return a + b;
    }

    // Three whole numbers
    public int add(int a, int b, int c) {
        System.out.println("add for three numbers: " + (a + b + c));
        return a + b + c;
    }

    // Two strings
    public String add(String a, String b) {
        System.out.println("add for two strings: " + a + b);
        return a + b;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        // The compiler picks each version from the arguments, before the program runs
        calc.add(3, 5);
        calc.add(1, 2, 3);
        calc.add("Hello ", "World");
    }
}
#include <cstdio>
#include <string>

// The same method name with different parameter lists: method overloading
class Calculator {
public:
    // Two whole numbers
    int add(int a, int b) const {
        std::printf("add for two numbers: %d\n", a + b);
        return a + b;
    }

    // Three whole numbers
    int add(int a, int b, int c) const {
        std::printf("add for three numbers: %d\n", a + b + c);
        return a + b + c;
    }

    // Two strings
    std::string add(const std::string& a, const std::string& b) const {
        std::printf("add for two strings: %s\n", (a + b).c_str());
        return a + b;
    }
};

int main() {
    Calculator calc;
    // The compiler picks each version from the arguments, before the program runs
    calc.add(3, 5);
    calc.add(1, 2, 3);
    calc.add("Hello ", "World");
    return 0;
}
// TypeScript has overload signatures over one body: the body checks the arguments
// when the program runs
class Calculator {
  add(a: number, b: number): number;
  add(a: number, b: number, c: number): number;
  add(a: string, b: string): string;
  add(a: number | string, b: number | string, c?: number): number | string {
    if (typeof a === "string" && typeof b === "string") {
      console.log(`add for two strings: ${a + b}`);
      return a + b;
    }
    if (typeof a === "number" && typeof b === "number") {
      if (c === undefined) {
        console.log(`add for two numbers: ${a + b}`);
        return a + b;
      }
      console.log(`add for three numbers: ${a + b + c}`);
      return a + b + c;
    }
    throw new Error("no add for these arguments");
  }
}

const calc = new Calculator();
calc.add(3, 5);
calc.add(1, 2, 3);
calc.add("Hello ", "World");
using System;

// The same method name with different parameter lists: method overloading
public class Calculator
{
    // Two whole numbers
    public int Add(int a, int b)
    {
        Console.WriteLine($"add for two numbers: {a + b}");
        return a + b;
    }

    // Three whole numbers
    public int Add(int a, int b, int c)
    {
        Console.WriteLine($"add for three numbers: {a + b + c}");
        return a + b + c;
    }

    // Two strings
    public string Add(string a, string b)
    {
        Console.WriteLine($"add for two strings: {a + b}");
        return a + b;
    }

    public static void Main()
    {
        var calc = new Calculator();
        // The compiler picks each version from the arguments, before the program runs
        calc.Add(3, 5);
        calc.Add(1, 2, 3);
        calc.Add("Hello ", "World");
    }
}
package main

import "fmt"

// Go has no overloading: each version gets a name of its own
type Calculator struct{}

// AddTwo adds two whole numbers
func (Calculator) AddTwo(a, b int) int {
	fmt.Printf("add for two numbers: %d\n", a+b)
	return a + b
}

// AddThree adds three whole numbers
func (Calculator) AddThree(a, b, c int) int {
	fmt.Printf("add for three numbers: %d\n", a+b+c)
	return a + b + c
}

// AddStrings joins two strings
func (Calculator) AddStrings(a, b string) string {
	fmt.Printf("add for two strings: %s\n", a+b)
	return a + b
}

func main() {
	calc := Calculator{}
	calc.AddTwo(3, 5)
	calc.AddThree(1, 2, 3)
	calc.AddStrings("Hello ", "World")
}

It prints:

add for two numbers: 8
add for three numbers: 6
add for two strings: Hello World

Overloading is a convenience of naming: three related operations share the name add instead of needing three names. The Java tutorial adds a warning worth keeping: "Overloaded methods should be used sparingly, as they can make code much less readable."

Watch One Call Reach Every Shape

Here is print_total_area with the listing's four shapes. Press print_total_area(shapes) and follow each shape.area() down to the area() of that object's own class while the total builds. Then press Add a Pentagon and run the same caller again: it counts the new shape without one changed line. Last, switch the caller to type checks, a version that asks each shape what it is, and run it with the Pentagon in the list.

shape.area() runs each object's own area(), so a new kind of shape works at once; a caller that checks types one by one leaves the Pentagon out without any error.

Polymorphism and the Open/Closed Principle

Polymorphism is what makes a well-known design rule work. Robert C. Martin states it as "A module should be open for extension but closed for modification.", and he writes that "It originated from the work of Bertrand Meyer." In practice it means you add new behaviour by adding new code, without editing code that already works.

print_total_area shows the rule at work. A Pentagon with its own area() joins the program and the caller does not change, because it never asks which kind of shape it has. A caller that checks types is the opposite: every new kind needs a new branch, and until someone writes it, the new kind is handled wrongly. Our test gave a Pentagon with sides of 2.0 to both. shape.area() counted it and printed a total of 133.99; the type checks skipped it with no error and printed 127.11. O — Open/Closed Principle covers the rule in full.

Common Mistakes

Mistake 1: checking types instead of calling the method.

if isinstance(shape, Circle):
    a = math.pi * shape.radius ** 2
elif isinstance(shape, Rectangle):
    a = shape.width * shape.height

Code like this has to be edited for every new kind of shape, and a kind nobody remembered falls through without a sound, as the Pentagon did above. Give each kind its own method and make one call:

a = shape.area()  # each shape knows its own area

Mistake 2: mixing up overloading and overriding. Overloading means the same name with different parameters, usually in one class, and the compiler chooses by the arguments. Overriding means the same name and the same parameters in a child class, and the object chooses while the program runs. Method Overloading vs Overriding compares the two side by side.

Mistake 3: missing an override without noticing. In Java, a child method meant to override calculatePay() but spelled caluclatePay() is a new method of its own, and the parent's version keeps running. A test showed exactly that: without @Override the code compiled and a manager was paid the parent's 1000.0. With @Override, javac stopped with caluclatePay() in Manager does not override or implement a method from a supertype. The Java documentation describes the annotation this way: it "Indicates that a method declaration is intended to override a method declaration in a supertype.", and compilers must report an error when the method overrides nothing. Write @Override on every method you mean to override.

Key Takeaways

  • Polymorphism lets one call run different code. Runtime polymorphism chooses by the object while the program runs; compile-time polymorphism chooses by the arguments when the code is compiled.
  • Runtime polymorphism comes from overriding. Code written against a general type, such as Shape, works with every specific type, including ones added later.
  • Overloading gives one name several parameter lists. Java, C++ and C# have it; Python and Go do not, and each has its own way to get the same effect.
  • A caller that checks types has to change for every new kind and can miss one without any error; a call to the object's own method does not.
  • Method Overloading vs Overriding comes next: the two side by side.