Programming Search⌘K

Conceptintro

Polymorphism

Also called polymorphic, subtype polymorphism, inclusion polymorphism, ad hoc polymorphism, coercion polymorphism, static polymorphism, dynamic polymorphism, many forms.

Polymorphism lets one name or one piece of code work with values of many types. The main kinds are subtype, parametric and ad hoc polymorphism, and some authors add coercion.

Applies to
core-languages

Idea

Code often does the same thing to values of different types: it computes the area of a square or a circle, takes the first item of a list of numbers or of strings, or prints an integer or a string. Polymorphism is the name for the ways a language lets one name or one piece of code serve all these types. Without it, a program needs one function for each type, with a different name for each. Python shows the main kinds in a few lines.

from functools import singledispatch


# Subtype polymorphism: one call, and the class of the object picks the method.
class Shape:
    def area(self) -> float:
        raise NotImplementedError


class Square(Shape):
    def __init__(self, side: float) -> None:
        self.side = side

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


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

    def area(self) -> float:
        return round(3.14159 * self.r * self.r, 2)


print([s.area() for s in [Square(2), Circle(1)]])


# Parametric polymorphism: one body of code for every element type.
def first[T](items: list[T]) -> T:
    return items[0]


print(first([3, 4]), first(["a", "b"]))


# Ad hoc polymorphism: a separate body of code for each type.
@singledispatch
def show(x: object) -> str:
    return "?"


@show.register
def _(x: int) -> str:
    return f"int {x}"


@show.register
def _(x: str) -> str:
    return f"str {x!r}"


print(show(1), show("a"), show(2.5))

# Operators are ad hoc too, and coercion turns the int into a float.
print("a" * 3, 2 * 3, 1 + 2.5)
Output
[4, 3.14]
3 a
int 1 str 'a' ?
aaa 6 3.5

The call s.area() runs the method of Square or of Circle, chosen by the object. first has one body that works for a list of any element type, because it does nothing with the items except return one. show has a separate body for each type, and the type of the argument picks one. The operator * repeats a string and multiplies numbers, and 1 + 2.5 converts the integer to a float before it adds.

How it works

One interface, many types. "In programming language theory and type theory, polymorphism allows a value or variable to have more than one type and allows a given operation to be performed on values of more than one type"1. "In object-oriented programming, polymorphism is the provision of one interface to entities of different data types"1. The Java tutorial takes the word from biology, where "an organism or species can have many different forms or stages"2.

Subtype polymorphism. A function written for a type T also accepts a value of a subtype S of T. "Subtyping (also called subtype polymorphism or inclusion polymorphism): when a name denotes instances of many different classes related by a common superclass"1. When the code calls a method, the class of the object picks the code: "At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method"3. In Java, the JVM "does not call the method that is defined by the variable's type"2. See subtyping and dynamic dispatch.

Parametric polymorphism. "Parametric polymorphism allows a function or a data type to be written generically, so that it can handle values uniformly without depending on their type"1. The code takes a type parameter, such as T, and works the same way for every type argument. "Any parametrically polymorphic function is necessarily restricted in what it can do, working on the shape of the data instead of its value"1. In C# and Java this is called generics, and in C++ it is done with templates1. See parametric polymorphism.

Ad hoc polymorphism. "Ad hoc polymorphism: defines a common interface for an arbitrary set of individually specified types"1. Overloaded functions and operators are the usual form: they "behave differently depending on the type of the argument to which they are applied"1, and each version is a separate function to the compiler1. In Python, functools.singledispatch makes "a single-dispatch generic function"4, and "the dispatch happens on the type of the first argument"4. In C, _Generic provides "a way to choose one of several expressions at compile time, based on a type of a controlling expression"5. See overloading.

Coercion. Implicit type conversion "has also been defined as a form of polymorphism"1, called coercion polymorphism. An operator that is defined for floats also accepts an integer, because the language converts the integer first. In JavaScript, "Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers)"6. See type conversion.

Static and dynamic polymorphism. "Polymorphism can be distinguished by when the implementation is selected: statically (at compile time) or dynamically (at run time, typically via a virtual function)"1. "Static polymorphism typically occurs in ad hoc polymorphism and parametric polymorphism, whereas dynamic polymorphism is usual for subtype polymorphism"1.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin has open classes and interfaces with overridden methods, generic functions and classes, and overloaded functions and operators. No example file exists because kotlinc is not installed.
SQLDoes not applyBuilt-in functions and operators accept several types, but a query defines no types, subtypes or generic code.
BashDoes not applyEvery Bash variable holds a string or an array of strings, so there are no types for code to choose between.
PowerShellNativePowerShell classes can inherit and override methods, and PowerShell can call overloaded .NET methods and generic .NET types. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no types of values.
CSSDoes not applyCSS properties take values of fixed types, and a style sheet defines no code that works on many types.
Regular expressionsDoes not applyA regular expression has no values and no types.
Language Verdict Mechanism
Python native methods chosen by class; duck typing; functools.singledispatch; type parameters for static checkers
JavaScript native methods found through the prototype chain; duck typing; implicit coercion
TypeScript native structural subtyping; generics; overload signatures
Java native virtual methods on classes and interfaces; generics; overloaded methods
Kotlin native open classes and interfaces; generics; overloaded functions and operators
C# native virtual methods and interfaces; generics; overloaded methods and operators
Go native interfaces that a type meets by its methods; type parameters; no overloading
Rust native traits, with static dispatch for generics and dynamic dispatch for dyn Trait; no overloading
C idiom function pointers in a struct; _Generic for overloads; arithmetic conversions
C++ native virtual functions; templates; overloaded functions and operators
Bash n/a every value is a string, so there are no types to choose between
PowerShell native .NET classes and interfaces; overloaded .NET methods; conversion of arguments
SQL n/a built-in functions take several types, but a query defines no types or subtypes
Regex n/a a pattern has no types
HTML n/a HTML has no types
CSS n/a CSS has no types in this sense

Java, C#, Kotlin and C++ have all three main kinds in the language. Go and Rust have subtype-like polymorphism through interfaces and traits, and parametric polymorphism through type parameters, but no overloading by type. Python and JavaScript choose a method by the object when the program runs, so any object with the right method works. C has only _Generic and function pointers, which the programmer must build into each design.

The example files show these differences. Python shows duck typing and a Protocol. JavaScript shows a call on objects that share no class, and the coercion of '5' + 9. TypeScript shows structural subtyping, a generic function and overload signatures. Java shows that an overload is chosen by the declared type, while an override is chosen by the object. C# shows a virtual method and an overloaded method. Go shows an interface and a function with a type parameter. Rust shows the same trait with static and with dynamic dispatch. C shows _Generic and a table of function pointers. C++ shows a virtual function, a template and an overload.

PythonGitHub
from typing import Protocol


class Speaker(Protocol):
    def speak(self) -> str: ...


# Neither class names Speaker, but both have speak, so both fit.
class Dog:
    def speak(self) -> str:
        return "woof"


class Robot:
    def speak(self) -> str:
        return "beep"


def talk(s: Speaker) -> str:
    return s.speak().upper()


print([talk(x) for x in (Dog(), Robot())])

# Duck typing: the call fails only when the program runs.
try:
    talk(42)  # a static checker reports this line
except AttributeError as e:
    print("AttributeError:", e)
Output
['WOOF', 'BEEP']
AttributeError: 'int' object has no attribute 'speak'
  • Verdict: native. talk calls speak on any object, and the class of the object picks the method. Speaker is a Protocol, so a class fits it when it has the method, with no base class. Python does not check the type when the program runs, so talk(42) fails only at the call. A static checker such as mypy reports that int is not a Speaker before the run.
#include <iostream>
#include <memory>
#include <numbers>
#include <string>
#include <vector>

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

struct Square : Shape {
    double side;
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
};

struct Circle : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return std::numbers::pi * r * r; }
};

// A template: the compiler makes a copy for each type argument.
template <typename T>
T first(const std::vector<T>& items) {
    return items[0];
}

// Overloads: the compiler picks one by the types of the arguments.
std::string show(int x) { return "int " + std::to_string(x); }
std::string show(const std::string& x) { return "string " + x; }

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Square>(2));
    shapes.push_back(std::make_unique<Circle>(1));
    std::cout.precision(3);
    for (const auto& s : shapes) {
        std::cout << s->area() << '\n';
    }

    std::cout << first(std::vector<int>{3, 4}) << ' '
              << first(std::vector<std::string>{"a", "b"}) << '\n';
    std::cout << show(1) << ", " << show(std::string("a")) << '\n';
}
Output
4
3.14
3 a
int 1, string a
  • Verdict: native. area is virtual, so the call through a Shape pointer runs the code of the object's class. first is a template, and the compiler makes first<int> and first<std::string>. The two show functions are overloads, and the compiler picks one by the type of the argument.
JavaGitHub
import java.util.List;

public class Main {
    static class Animal {
        String sound() { return "..."; }
    }

    static class Cat extends Animal {
        @Override
        String sound() { return "meow"; }
    }

    // Overloads: the compiler picks one by the declared type of the argument.
    static String describe(Object o) { return "object"; }

    static String describe(String s) { return "string"; }

    // Generics: one body for every element type.
    static <T> T first(List<T> items) { return items.get(0); }

    public static void main(String[] args) {
        Animal a = new Cat();
        System.out.println(a.sound()); // the object picks the override

        Object o = "hi";
        System.out.println(describe(o) + " " + describe("hi"));

        System.out.println(first(List.of(3, 4)) + " " + first(List.of("a", "b")));
    }
}
Output
meow
object string
3 a
  • Verdict: native. The variable a has the declared type Animal, but the object is a Cat, so the call runs Cat.sound. describe(o) calls the Object overload, although o holds a string, because the compiler chooses an overload by the declared type Object. first is a generic method, and the compiler infers T for each call.
#include <stdio.h>

// _Generic: the compiler picks an expression by the type of the argument.
#define show(x) _Generic((x), int: show_int, double: show_double, const char *: show_str, char *: show_str)(x)

static void show_int(int x) { printf("int %d\n", x); }
static void show_double(double x) { printf("double %.1f\n", x); }
static void show_str(const char *x) { printf("string %s\n", x); }

// A table of function pointers: the object carries its own operations.
struct shape;
struct shape_ops {
    double (*area)(const struct shape *);
    const char *name;
};
struct shape {
    const struct shape_ops *ops;
    double size;
};

static double square_area(const struct shape *s) { return s->size * s->size; }
static double circle_area(const struct shape *s) { return 3.14159 * s->size * s->size; }

static const struct shape_ops square_ops = {square_area, "square"};
static const struct shape_ops circle_ops = {circle_area, "circle"};

int main(void) {
    show(1);
    show(2.5);
    show("a");

    struct shape shapes[] = {{&square_ops, 2}, {&circle_ops, 1}};
    for (int i = 0; i < 2; i++) {
        printf("%s %.2f\n", shapes[i].ops->name, shapes[i].ops->area(&shapes[i]));
    }
    return 0;
}
Output
int 1
double 2.5
string a
square 4.00
circle 3.14
  • Verdict: idiom. C has no overloading and no virtual functions. The show macro uses _Generic, which picks a function by the type of the argument when the program compiles. Each struct shape points to a table of operations, so the call ops->area runs the function of the object, as a virtual call does in C++.
using System;
using System.Collections.Generic;

Shape[] shapes = { new Square(2), new Circle(1) };
foreach (var s in shapes)
{
    Console.WriteLine($"{s.GetType().Name} {s.Area():F2}");
}

Console.WriteLine($"{Poly.Show(1)} {Poly.Show("a")} {Poly.Show(2.5)}");
Console.WriteLine($"{Poly.First(new List<int> { 3, 4 })} {Poly.First(new List<string> { "a", "b" })}");

// Overloads must be methods of a type; local functions cannot be overloaded.
static class Poly
{
    public static string Show(int x) => $"int {x}";
    public static string Show(string x) => $"string {x}";
    public static string Show(object x) => "object";

    public static T First<T>(List<T> items) => items[0];
}

abstract class Shape
{
    public abstract double Area();
}

class Square(double side) : Shape
{
    public override double Area() => side * side;
}

class Circle(double r) : Shape
{
    public override double Area() => Math.PI * r * r;
}
Output
Square 4.00
Circle 3.14
int 1 string a object
3 a
  • Verdict: native. Area is abstract in Shape, and each class overrides it, so the run-time type of the object picks the code. Show has three overloads. Show(2.5) calls the object version, because no overload takes a double. First<T> is a generic method.
JavaScriptGitHub
// The objects share no class; each has an area method.
const shapes = [
  { side: 2, area() { return this.side * this.side; } },
  { r: 1, area() { return Math.round(Math.PI * this.r * this.r * 100) / 100; } },
];
console.log(shapes.map((s) => s.area()));

// One operator, several types: + adds numbers and joins strings.
console.log(2 + 3, "a" + "b");

// Coercion: the number is converted to a string, or the string to a number.
console.log("5" + 9, "5" * 9, Number("5") + 9);
Output
[ 4, 3.14 ]
5 ab
59 45 14
  • Verdict: native. JavaScript finds the method on the object when the program runs, so any object with area works. + adds two numbers and joins two strings. With a string and a number, + converts the number to a string, but * converts the string to a number. Number("5") makes the conversion explicit.
TypeScriptGitHub
// Structural subtyping: a type fits Shape when it has the members.
interface Shape {
  area(): number;
}

class Square {
  side: number;
  constructor(side: number) {
    this.side = side;
  }
  area(): number {
    return this.side * this.side;
  }
}

const rect = { w: 2, h: 3, area() { return this.w * this.h; } };

function total(shapes: Shape[]): number {
  return shapes.reduce((sum, s) => sum + s.area(), 0);
}
console.log(total([new Square(2), rect]));

// Parametric polymorphism: one body for every element type.
function first<T>(items: T[]): T {
  return items[0];
}
const n: number = first([3, 4]);
const s: string = first(["a", "b"]);
console.log(n, s);

// Overload signatures: one implementation, a type for each call form.
function double(x: number): number;
function double(x: string): string;
function double(x: number | string): number | string {
  return typeof x === "number" ? x * 2 : x + x;
}
console.log(double(21), double("ab"));
Output
10
3 a
42 abab
  • Verdict: native. Square and the object rect do not name Shape, but both have area, so both fit. first takes a type parameter T, and the checker gives first([3, 4]) the type number. The two overload signatures give double(21) the type number and double("ab") the type string. The overloads have one body, which tests the type with typeof.
package main

import (
	"fmt"
	"math"
)

// A type meets Shape when it has the method; it does not name Shape.
type Shape interface {
	Area() float64
}

type Square struct{ Side float64 }

func (s Square) Area() float64 { return s.Side * s.Side }

type Circle struct{ R float64 }

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

// A type parameter: one body for every element type.
func First[T any](items []T) T {
	return items[0]
}

// A constraint limits the type arguments to the types in a set.
func Sum[T int | float64](xs []T) T {
	var s T
	for _, x := range xs {
		s += x
	}
	return s
}

func main() {
	for _, s := range []Shape{Square{2}, Circle{1}} {
		fmt.Printf("%T %.2f\n", s, s.Area())
	}
	fmt.Println(First([]int{3, 4}), First([]string{"a", "b"}))
	fmt.Println(Sum([]int{1, 2}), Sum([]float64{1.5, 2}))
}
Output
main.Square 4.00
main.Circle 3.14
3 a
3 3.5
  • Verdict: native. Square and Circle meet Shape because they have Area, and a value of type Shape holds either one. First and Sum take a type parameter. The constraint int | float64 lets Sum use +. Go has no overloading, so a function name has one signature.
RustGitHub
trait Shape {
    fn area(&self) -> f64;
}

struct Square(f64);
struct Circle(f64);

impl Shape for Square {
    fn area(&self) -> f64 {
        self.0 * self.0
    }
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.0 * self.0
    }
}

// Static dispatch: the compiler makes a copy of the function for each type.
fn show_static<T: Shape>(s: &T) -> String {
    format!("{:.2}", s.area())
}

// Dynamic dispatch: the call goes through the vtable of the trait object.
fn show_dyn(s: &dyn Shape) -> String {
    format!("{:.2}", s.area())
}

fn main() {
    println!("{} {}", show_static(&Square(2.0)), show_static(&Circle(1.0)));

    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
    let areas: Vec<String> = shapes.iter().map(|s| show_dyn(s.as_ref())).collect();
    println!("{}", areas.join(" "));
}
Output
4.00 3.14
4.00 3.14
  • Verdict: native. show_static has a type parameter with the bound Shape, so the compiler makes one copy for Square and one for Circle. show_dyn takes a &dyn Shape, and the call finds area when the program runs. A Vec<Box<dyn Shape>> can hold values of both types, but a Vec<T> holds one type. Rust has no overloading of functions.
  • Duck typing. A dynamic language can skip the types and call the method: with duck typing, "the method or attribute is simply called or used"7, and the code does not test the type first. Go makes a similar check when the program compiles: "A variable of interface type can store a value of any type that is in the type set of the interface"8, and a type is in that set when it has the methods.
  • Bounded polymorphism. "The interaction between parametric polymorphism and subtyping leads to the concepts of type variance and bounded quantification"1. A type parameter can require a subtype of an interface, such as T extends Comparable<T>.
  • Multiple dispatch. Most object systems choose a method by one object only, but some, "such as Common Lisp Object System, provide multiple dispatch, under which method calls are polymorphic in all arguments"1.
  • Row polymorphism. Row polymorphism "is a similar, but distinct concept from subtyping"1: a function accepts any record that has certain fields and keeps the types of the other fields. See row polymorphism.

Pitfalls

  • An overload is chosen by the declared type. With overloading, "one of several functions is chosen at compile time based on the types of the arguments"5, but an override is chosen by the object when the program runs2. In Java, describe(Object o) and describe(String s) with an argument declared as Object call the Object version even when the object is a string. The Java example shows this.
  • Unwanted coercion. In JavaScript, the string '5' plus the number 9 gives the string '59', because "JavaScript has coerced the 9 from a number into a string"6. Convert explicitly, for example with Number()6.
  • A method on a value that lacks it. With duck typing, a call on an object without the method fails only when the program runs. A static checker with Protocol in Python, or an interface in Go and TypeScript, finds the error before the run.
  • Changing the meaning of an operator. An overloaded operator can do work that the reader does not expect, such as * on a string. Overload an operator only when its meaning for the type is clear. See operator overloading.

Cost

Static polymorphism costs nothing when the program runs: the compiler picks the code for each call. For generics, "The compiler generates nongeneric implementations of functions and methods for each concrete type"9, as C++ does for templates1, so the program grows with each type it uses. Dynamic polymorphism adds a lookup to each call. In Rust, "This lookup incurs a runtime cost"9 that static dispatch does not have, and dynamic dispatch "prevents the compiler from choosing to inline a method"9. "Static polymorphism executes faster, because there is no dynamic dispatch overhead, but requires additional compiler support"1.

History

Christopher Strachey described ad hoc polymorphism and parametric polymorphism in Fundamental Concepts in Programming Languages, where they are "the two main classes" of polymorphism1. Ad hoc polymorphism was a feature of ALGOL 68, and parametric polymorphism was the core of the type system of ML1. In 1985, Peter Wegner and Luca Cardelli introduced the term inclusion polymorphism for subtypes and inheritance, and named Simula as the first language with it1.

References

  1. Polymorphism (computer science), Wikipedia, Introduction; History; Forms; Static and dynamic polymorphism
  2. Polymorphism, The Java Tutorials, Whole page
  3. Polymorphism, C# fundamentals, Introduction
  4. functools, Python 3.14 documentation, functools.singledispatch
  5. Generic selection, C reference, cppreference.com, Syntax; Notes
  6. Type coercion, MDN Web Docs Glossary, Whole entry
  7. Glossary, Python 3.14 documentation, duck-typing; generic function
  8. The Go Programming Language Specification, Interface types; Type parameter declarations
  9. Using Trait Objects to Abstract over Shared Behavior, The Rust Programming Language, Performing Dynamic Dispatch

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/8WZW5P/text.yaml