Conceptcore
Subtyping
Also called subtype polymorphism, inclusion polymorphism, Liskov substitution principle, variance.
A type S is a subtype of a type T when a value of S can be used wherever a value of T is expected. Code written for T then works for every subtype, and the compiler or the runtime checks the uses.
- Applies to
- core-languages
Idea
A type S is a subtype of a type T, written S <: T, when a value of S can be used wherever a value of T is expected. Code that is written for T then works for every subtype of T, including subtypes that did not exist when the code was written.
Barbara Liskov stated the idea as a substitution property. Suppose that for each object o1 of type S there is an object o2 of type T, such that every program P defined in terms of T behaves the same when o1 replaces o2. Then S is a subtype of T.1 This rule is known as the Liskov substitution principle. It is a rule about behaviour, not only about names and signatures. Liskov and Wing later made it precise: a property that you can prove about the objects of T must also hold for the objects of S.2
In the Java program below, report is written for the interface Shape. It works for Square and for Circle, because each class implements Shape.
import java.util.List;
public class Main {
interface Shape {
double area();
}
record Square(double side) implements Shape {
public double area() {
return side * side;
}
}
record Circle(double radius) implements Shape {
public double area() {
return Math.PI * radius * radius;
}
}
static void report(Shape shape) {
System.out.printf("%s %.2f%n", shape.getClass().getSimpleName(), shape.area());
}
public static void main(String[] args) {
List<Shape> shapes = List.of(new Square(2), new Circle(1));
for (Shape shape : shapes) {
report(shape);
}
}
}
Square 4.00
Circle 3.14
The call shape.area() selects the method of the object, not the method of the static type. This is dynamic dispatch. Subtyping and dynamic dispatch together are called subtype polymorphism, or inclusion polymorphism.
How it works
Cardelli gave the basic rules in a type system with records and functions.3 Three of them carry most of the idea:
- Subsumption. If a value has type S and S <: T, then the value also has type T. A function that takes a T accepts it.
- Records. A record type is a subtype of another record type when it has all the fields of the other type, and possibly more, and the types of the common fields are subtypes. In Cardelli's example,
car = {age: int, speed: int, fuel: string}is a subtype ofvehicle = {age: int, speed: int}. - Functions. A function type σ→τ is a subtype of σ'→τ' when σ' <: σ and τ <: τ'. The argument goes the opposite way to the result. Variance, below, explains why.
Subtyping and inheritance
Inheritance and subtyping are different things. Inheritance reuses the code of a class in another class. Subtyping is a relation between types that says one can stand in for the other. Liskov notes that "subclass" and "superclass" are linguistic ideas, while "subtype" and "supertype" are semantic ideas. A subclass can implement a subtype, but a programmer can also use a subclass only to reuse an implementation.14 A subclass that overrides a method and changes its meaning is still a subclass, but it is not a behavioural subtype. The Pitfalls section shows an example.
Nominal and structural subtyping
A language decides S <: T in one of two ways.
- Nominal subtyping. S is a subtype of T only when the program says so. In Java, a class is a subtype of its superclass and of the interfaces that it declares in
extendsandimplements.5 C#, Kotlin and C++ work the same way. Two classes with the same members are unrelated unless one names the other. - Structural subtyping. S is a subtype of T when S has the members that T requires. Nobody declares the relation. Liskov described this "grouping approach" in 1987: a module accepts any type that supplies the operations that it needs.6 TypeScript bases type compatibility on structural subtyping.7 In Go, a type implements an interface when its method set has the methods of the interface, and a value is assignable to an interface type when its type implements the interface.89 No
implementsdeclaration exists.
Python has both. At run time, isinstance follows the class hierarchy, which is nominal. An abstract base class can also accept an unrelated class as a "virtual subclass" through register.12 For static checks, PEP 544 adds protocol classes, which are structural, to the nominal rules of PEP 484.10 A type checker accepts any class with the members of the protocol. At run time, a protocol with the decorator runtime_checkable checks only that the attributes are present, and ignores their signatures.11 The Python example shows both checks.
In TypeScript, an object with more fields than a type requires is a subtype, as in Cardelli's rule for records. The function norm below takes a Point. It accepts an object with a third field and an instance of an unrelated class.
interface Point {
x: number;
y: number;
}
class Vector {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
function norm(p: Point): number {
return Math.hypot(p.x, p.y);
}
const point3 = { x: 3, y: 4, z: 12 };
console.log(norm(point3));
console.log(norm(new Vector(6, 8)));
5
10
JavaScript has no static types. Its instanceof operator walks the prototype chain of the object, and gives true when it finds the prototype object of the constructor.13 The JavaScript example shows how to change the answer at run time.
At the machine level
In C++, a pointer to a derived class converts to a pointer to a base class. The result points to the base class subobject of the object.14 The Itanium C++ ABI allocates the primary base class first.15 So with single inheritance the base subobject is at offset zero, and the conversion does not change the address. A second base class is at a different offset, so a conversion to it adds that offset (see the C++ example).
A call of a virtual function goes through a virtual table. Each object of a dynamic class holds a pointer to a table of information for its class, which includes the addresses of its virtual functions.16 A call loads the table pointer from the object, loads the address from the table, and calls it. The caller does not need to know the dynamic class.
A Go variable of interface type has a static type, the interface, and a dynamic type, the type of the value that it holds at run time.17 The specification does not say how the pair is stored. Russ Cox describes the implementation: an interface value is two words, a pointer to an interface table and a pointer to the data. The table holds the function pointers of the methods.18
C has no subtyping. A common idiom puts the "base" struct as the first member of the "derived" struct. A pointer to a structure, suitably converted, points to its first member, and there is no padding at the start of a structure.19 So a struct square * converts to a pointer to its first member, a struct shape. The C example shows the idiom. The compiler does not check that the cast back is to the right type.
Variance
Variance says how subtyping of parts gives subtyping of a whole. Take Cat <: Animal.
- Results are covariant. A method that returns a Cat can replace a method that returns an Animal. The caller expects an Animal and gets one.
- Parameters are contravariant. A function that accepts any Animal can replace a function that accepts a Cat. The caller passes a Cat, and the function can handle it.
Liskov and Wing list these as the signature rules of a subtype: contravariance of arguments, covariance of the result, and a rule for exceptions. Their definition adds rules for behaviour: pre-conditions, post-conditions, invariants and history constraints.20 The signature rules only prevent type errors. They do not make a stack a subtype of a queue, even when both have put and get of the right types.2
C++ and Java allow covariant return types. An override in C++ can return a pointer or reference to a class derived from the class that the overridden function returns.21 In Java, the return type of an override must be return-type-substitutable for the return type of the overridden method, which for reference types allows a subtype.22 The Java and C++ examples show this.
A mutable container must be invariant. You read elements from it, which is a covariant use, and you write elements to it, which is a contravariant use. Only the same type is safe for both. Languages handle this in several ways.
- Covariant arrays with a check at run time. In Java, if S <: T for reference types, then S[] <: T[].23 The language pays for this with a check on every store into an array of references. A store of the wrong type throws
ArrayStoreException.2425 C# arrays of reference types are covariant in the same way, with the same kind of check, and a wrong store throwsSystem.ArrayTypeMismatchException. Arrays of value types are not covariant: no conversion exists fromint[]toobject[].26 The first two pitfalls show both. - Invariant arrays. Kotlin's
Array<T>is invariant inT, soArray<Int>is not anArray<Any>.27 - Variance on read-only interfaces. Kotlin declares
List<out E>, which gives only read access, soList<Int>is aList<Any>.28 In C#, anIEnumerable<string>is anIEnumerable<object>, and anAction<object>is anAction<string>.29 Java decides variance at each use with wildcards. Generics covers generic variance and the invariance ofList<Integer>. - Bivariant parameters. When TypeScript compares two function types, it accepts the assignment if either parameter type is assignable to the other. The handbook calls this unsound and says that it allows many common JavaScript patterns.30 The
strictFunctionTypesoption checks parameters of function types contravariantly. It does not apply to methods, which stay bivariant.3132 The fourth pitfall shows the result. - Lifetimes only. Rust has subtyping only between lifetimes and types with higher-ranked lifetimes. If you erase the lifetimes, the only subtyping is type equality.33
&'static stris a subtype of&'a str. The variance table of the Rust Reference makes&'a Tcovariant inT,&'a mut Tinvariant inT, andfn(T)contravariant inT.34 Traits are not types in a subtype relation. ABox<dyn Trait>is made by a coercion.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | |
| SQL | Absent | A table or a row type has no subtype relation in the SQL of the examples. Alternative: PostgreSQL table inheritance, where a child table created with INHERITS has the columns of its parent and a query on the parent can include the rows of the children. |
| Bash | Does not apply | Bash has no types, only strings and arrays of strings. |
| PowerShell | Native | |
| HTML | Does not apply | Markup has no types. |
| CSS | Does not apply | Style rules have no types. |
| Regular expressions | Does not apply | A pattern has no types. |
The example files show subtyping in each language. The table gives the verdict for each tier 1 language.
| Language | Verdict | Form |
|---|---|---|
| Python | native | classes, with isinstance at run time; ABCs with register; protocols checked by a type checker1012 |
| JavaScript | native | class ... extends, the prototype chain and instanceof; no static check13 |
| TypeScript | native | structural; any value with the required members is compatible7 |
| Java | native | nominal, with extends and implements; covariant arrays523 |
| C | idiom | a struct whose first member is the base struct19 |
| C++ | native | nominal, with base classes and virtual functions14 |
| C# | native | nominal, with base classes and interfaces; covariant arrays of reference types26 |
| Go | native | structural, through interfaces; no subtyping between struct types8 |
| Rust | native | lifetimes only; traits give polymorphism without a subtype relation33 |
| Kotlin | native | nominal, with open classes and interfaces; declaration-site variance27 |
| PowerShell | native | classes with single inheritance, and -is35 |
| Bash | n/a | no types |
| SQL | absent | no subtype relation between tables or row types; PostgreSQL has table inheritance36 |
| Regex | n/a | a pattern has no types |
| HTML | n/a | markup has no types |
| CSS | n/a | style rules have no types |
PostgreSQL lets a table inherit the columns of a parent table with INHERITS, and a query on the parent can include the rows of the children. The documentation calls the lack of index and foreign key support across the hierarchy a serious limitation.36
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side * self.side
class Circle:
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return 3.14159 * self.radius * self.radius
@runtime_checkable
class HasArea(Protocol):
def area(self) -> float: ...
class Fake:
area = "not a method"
print(isinstance(Square(2), Shape))
print(isinstance(Circle(1), Shape))
Shape.register(Circle)
print(isinstance(Circle(1), Shape))
print(Shape in Circle.__mro__)
print(isinstance(Circle(1), HasArea))
print(isinstance(Fake(), HasArea))
True
False
True
False
True
True
- Verdict: native. At run time,
isinstancefollows the class hierarchy.Squareis aShapebecause it namesShapeas a base class. Shape.register(Circle)makesCirclea virtual subclass.isinstanceaccepts it, butShapeis not in its method resolution order.- A type checker such as mypy treats
HasAreastructurally: any class with anareamethod that returnsfloatmatches. - At run time,
runtime_checkablechecks only that the attribute exists.Fakepasses, although itsareais a string.
#include <iostream>
#include <memory>
#include <vector>
struct Shape {
virtual ~Shape() = default;
virtual double area() const = 0;
virtual Shape* clone() const = 0;
};
struct Square : Shape {
double side;
explicit Square(double s) : side(s) {}
double area() const override { return side * side; }
Square* clone() const override { return new Square(*this); }
};
struct Named { const char* name = "named"; };
struct Tile : Square, Named {
explicit Tile(double s) : Square(s) {}
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Square>(2));
shapes.push_back(std::make_unique<Tile>(3));
for (const auto& s : shapes) std::cout << s->area() << "\n";
Square square(4);
std::unique_ptr<Square> copy(square.clone());
std::cout << copy->side << "\n";
Tile tile(1);
void* whole = &tile;
std::cout << (static_cast<void*>(static_cast<Square*>(&tile)) == whole) << "\n";
std::cout << (static_cast<void*>(static_cast<Named*>(&tile)) == whole) << "\n";
}
4
9
4
1
0
- Verdict: native. Subtyping is nominal, through public base classes. A virtual function dispatches on the dynamic type.
Square::clonereturnsSquare*whereShape::clonereturnsShape*. This is a covariant return type, so the copy needs no cast.- A pointer to
Tileconverts to a pointer to its first base,Square, at the same address. The conversion to the second base,Named, changes the address. - Pass a polymorphic object by reference or by pointer. A copy by value slices it, as the concept page shows.
import java.util.List;
public class Main {
interface Shape {
double area();
Shape scaled(double factor);
}
record Square(double side) implements Shape {
public double area() {
return side * side;
}
public Square scaled(double factor) {
return new Square(side * factor);
}
}
record Circle(double radius) implements Shape {
public double area() {
return Math.PI * radius * radius;
}
public Circle scaled(double factor) {
return new Circle(radius * factor);
}
}
public static void main(String[] args) {
List<Shape> shapes = List.of(new Square(2), new Circle(1));
for (Shape shape : shapes) {
System.out.printf("%s %.2f%n", shape.getClass().getSimpleName(), shape.area());
}
Square big = new Square(1).scaled(3);
System.out.println(big.side());
Object any = big;
System.out.println(any instanceof Shape);
if (any instanceof Square square) {
System.out.println(square.area());
}
}
}
Square 4.00
Circle 3.14
3.0
true
9.0
- Verdict: native. Subtyping is nominal. A class is a subtype of its superclass and of the interfaces in its
implementsclause. Square.scaledoverridesShape.scaledwith the return typeSquare. This is a covariant return type, sonew Square(1).scaled(3)needs no cast.instanceofwith a pattern tests the dynamic type and binds a variable of the subtype.- Arrays are covariant and generic types are invariant. The concept page shows the
ArrayStoreExceptionthat covariant arrays allow.
#include <stdio.h>
struct shape {
const char *name;
double (*area)(const struct shape *self);
};
struct square {
struct shape base;
double side;
};
struct circle {
struct shape base;
double radius;
};
static double square_area(const struct shape *self) {
const struct square *sq = (const struct square *)self;
return sq->side * sq->side;
}
static double circle_area(const struct shape *self) {
const struct circle *c = (const struct circle *)self;
return 3.141592653589793 * c->radius * c->radius;
}
static void report(const struct shape *s) {
printf("%s %.2f\n", s->name, s->area(s));
}
int main(void) {
struct square sq = {{"square", square_area}, 2.0};
struct circle c = {{"circle", circle_area}, 1.0};
const struct shape *shapes[] = {&sq.base, (const struct shape *)&c};
for (size_t i = 0; i < sizeof shapes / sizeof shapes[0]; i++) {
report(shapes[i]);
}
printf("%d\n", (void *)&sq == (void *)&sq.base);
return 0;
}
square 4.00
circle 3.14
1
- Verdict: idiom. C has no subtyping. The "base" struct is the first member of each "derived" struct.
- A pointer to a structure, converted, points to its first member, and a structure has no padding before its first member. So
&sq.baseand&sqhave the same address. - The function pointer in
struct shapeplays the part of a virtual table. - The compiler does not check the cast from
struct shape *back tostruct square *. A cast to the wrong struct type gives undefined behaviour.
Shape[] shapes = { new Square(2), new Circle(1) };
foreach (Shape shape in shapes)
{
Console.WriteLine($"{shape.GetType().Name} {shape.Area():F2}");
}
IEnumerable<string> names = new List<string> { "Ada", "Grace" };
IEnumerable<object> items = names;
Console.WriteLine(string.Join(", ", items));
Action<object> print = value => Console.WriteLine($"got {value}");
Action<string> printName = print;
printName("Ada");
object any = new Square(3);
if (any is Square square)
{
Console.WriteLine(square.Side);
}
abstract class Shape
{
public abstract double Area();
}
class Square(double side) : Shape
{
public double Side => side;
public override double Area() => side * side;
}
class Circle(double radius) : Shape
{
public override double Area() => Math.PI * radius * radius;
}
Square 4.00
Circle 3.14
Ada, Grace
got Ada
3
- Verdict: native. Subtyping is nominal, through base classes and interfaces. A method must be
virtualorabstractto be overridden. IEnumerable<out T>is covariant, so a sequence of strings is a sequence of objects.Action<in T>is contravariant, so an action that takes any object can act on strings.- Variance of generic types applies only to interfaces and delegates, and only to reference types.
- Arrays of reference types are covariant, with a check on each store. The concept page shows the
ArrayTypeMismatchException.
class Shape {
area() {
return 0;
}
describe() {
return `${this.constructor.name} ${this.area()}`;
}
}
class Square extends Shape {
constructor(side) {
super();
this.side = side;
}
area() {
return this.side * this.side;
}
}
const square = new Square(3);
console.log(square instanceof Square, square instanceof Shape);
console.log(square.describe());
console.log(Object.getPrototypeOf(Square.prototype) === Shape.prototype);
const plain = { area: () => 7 };
console.log(plain instanceof Shape);
Object.setPrototypeOf(plain, Shape.prototype);
console.log(plain instanceof Shape, plain.describe());
true true
Square 9
true
false
true Shape 7
- Verdict: native.
class Square extends Shapesets the prototype ofSquare.prototypetoShape.prototype, so aSquareinherits the methods ofShape. instanceofwalks the prototype chain of the object. It says nothing about the members of the object.Object.setPrototypeOfchanges the chain at run time, so a plain object becomes an instance ofShape.- No static check exists. Any object with the right methods works in a call, which is duck typing.
interface Shape {
area(): number;
}
class Square {
side: number;
constructor(side: number) {
this.side = side;
}
area(): number {
return this.side * this.side;
}
}
function total(shapes: readonly Shape[]): number {
let sum = 0;
for (const shape of shapes) {
sum += shape.area();
}
return sum;
}
const circle = { radius: 1, area: () => Math.PI };
console.log(total([new Square(2), circle]).toFixed(2));
const squares: readonly Square[] = [new Square(1), new Square(3)];
const shapes: readonly Shape[] = squares;
console.log(total(shapes));
type Printer = (value: string) => void;
const printAny = (value: unknown): void => console.log("got", value);
const printName: Printer = printAny;
printName("Ada");
7.14
10
got Ada
- Verdict: native. Subtyping is structural.
Squaredoes not declareimplements Shape, and the object literal has no class, but both havearea, so both areShapevalues. - A
readonly Square[]is areadonly Shape[]. - A function that accepts
unknowncan stand in for a function that acceptsstring, because parameters are contravariant. - The parameters of methods are checked bivariantly. The concept page shows the run time error that this allows.
- The runner strips the types and does not run the type checker.
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
}
type Square struct{ Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
type Circle struct{ Radius float64 }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
type Tile struct {
Square
Colour string
}
func total(shapes []Shape) float64 {
sum := 0.0
for _, s := range shapes {
sum += s.Area()
}
return sum
}
func main() {
shapes := []Shape{Square{2}, Circle{1}, Tile{Square{1}, "red"}}
fmt.Printf("%.2f\n", total(shapes))
for _, s := range shapes {
fmt.Printf("%T\n", s)
}
var s Shape = Square{3}
if sq, ok := s.(Square); ok {
fmt.Println(sq.Side)
}
_, ok := s.(Circle)
fmt.Println(ok)
}
8.14
main.Square
main.Circle
main.Tile
3
false
- Verdict: native. A type implements an interface when it has the methods of the interface. No declaration names the interface.
TileembedsSquare, so it gets the methodAreaand implementsShape. Embedding is not subtyping: aTileis not assignable to a variable of typeSquare.- A type assertion
s.(Square)tests the dynamic type of an interface value. - Struct types have no subtype relation. Only interface types accept values of other types.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
struct Circle(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.0 * self.0
}
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let owned = String::from("hello there");
let fixed: &'static str = "hi";
println!("{}", longest(&owned, fixed));
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("{total:.2}");
}
hello there
7.14
- Verdict: native. Rust has subtyping only between lifetimes.
&'static stris a subtype of&'a str, sofixedis accepted wherelongestexpects&'a str. - A trait is not a supertype of the types that implement it.
Box<Square>becomesBox<dyn Shape>by an unsizing coercion, and the trait object callsareathrough a vtable. &'a mut Tis invariant inT, which is the rule for mutable containers.
interface Shape {
fun area(): Double
fun scaled(factor: Double): Shape
}
open class Square(val side: Double) : Shape {
override fun area() = side * side
override fun scaled(factor: Double): Square = Square(side * factor)
}
class Tile(side: Double, val colour: String) : Square(side)
fun total(shapes: List<Shape>): Double = shapes.sumOf { it.area() }
fun main() {
val squares: List<Square> = listOf(Square(1.0), Tile(2.0, "red"))
println(total(squares))
val big: Square = Square(1.0).scaled(3.0)
println(big.side)
for (shape in squares) {
println(shape::class.simpleName)
}
val name: String = "Ada"
val maybe: String? = name
println(maybe?.length)
val numbers: Array<Int> = arrayOf(1, 2)
val anything: Array<out Any> = numbers
println(anything.joinToString())
}
5.0
3.0
Square
Tile
3
1, 2
- Verdict: native. Subtyping is nominal. A class is final unless it is
open, so a class can have a subclass only when its author allows it. List<out E>is covariant, sototalaccepts aList<Square>where it expects aList<Shape>.Array<T>is invariant. The projectionArray<out Any>gives a view ofArray<Int>that can only be read.- An override can return a subtype, as
Square.scaleddoes. AStringis assignable to aString?.
class Shape {
[double] Area() { return 0 }
[string] Describe() { return '{0} {1}' -f $this.GetType().Name, $this.Area() }
}
class Square : Shape {
[double] $Side
Square([double] $side) { $this.Side = $side }
[double] Area() { return $this.Side * $this.Side }
}
class Tile : Square {
[string] $Colour
Tile([double] $side, [string] $colour) : base($side) { $this.Colour = $colour }
}
$shapes = [Shape[]] @([Square]::new(3), [Tile]::new(2, 'red'))
foreach ($shape in $shapes) { $shape.Describe() }
$shapes[1] -is [Square]
$shapes[1] -is [Shape]
[Shape] $view = [Square]::new(5)
$view.GetType().Name
$view.Area()
Square 9
Tile 4
True
True
Square
25
- Verdict: native. A class can inherit from one base class with
class Square : Shape. The derived class can override a method of the base class. -istests the dynamic type against the class and its base classes.- A variable typed
[Shape]holds aSquare, and a call ofAreauses the method ofSquare. - A constructor calls the constructor of its base class with
: base(...).
Variations and related ideas
- Subtyping and generics. Parametric polymorphism makes one definition work for all types, and subtyping makes one type stand in for another. Bounded type parameters, such as
<T extends Comparable<T>>, join the two. Generics describes generics and their variance. - Width and depth. Cardelli's rule for records allows two things: more fields (width) and more specific types for the common fields (depth).3 His records are values that a program does not update. For a field that a program can write, depth subtyping has the problem of a mutable container, which Variance explains. Immutability describes read-only data.
- Functions as values. The rule for function types matters most when functions are passed as values, as in callbacks. Higher-order function covers them.
- Nullable types. A type that allows null can act as a supertype of the same type without null. The Kotlin example assigns a
Stringto aString?. Null reference covers null checks. - Duck typing. A dynamic language without static checks does not need a declared relation. A call works when the object has the method. The error, if any, comes at run time. Static and dynamic typing explains the difference.
- Numeric widening. Java also defines subtyping among the primitive types.
longis a supertype ofint, anddoubleis a supertype offloat.38 This relation is separate from subtyping between classes.
Pitfalls
A wrong store into a covariant array
A String[] is an Object[] in Java, so the compiler accepts a store of an Integer through the Object[] view. The JVM checks the store and throws ArrayStoreException.2425
This code raises ArrayStoreException, on purpose.
public class Main {
public static void main(String[] args) {
String[] names = {"Ada", "Grace"};
Object[] items = names;
items[0] = Integer.valueOf(42);
System.out.println(names[0].length());
}
}
The program stops with java.lang.ArrayStoreException: java.lang.Integer. Use a List<String> instead. A generic list is invariant, so the compiler rejects the assignment (Generics shows this).
The same store in C#
C# arrays of reference types are covariant too. The store compiles and throws at run time.26
This code raises ArrayTypeMismatchException, on purpose.
string[] names = { "Ada", "Grace" };
object[] items = names;
items[0] = new object();
Console.WriteLine(names[0].Length);
The program stops with System.ArrayTypeMismatchException. A read-only view, such as IEnumerable<object>, is safe, because it has no store.29
A subclass that breaks the contract of its base
A class Square that extends Rectangle looks natural: every square is a rectangle. But a mutable Rectangle promises that set_width changes the width and keeps the height. A Square must keep its sides equal, so it breaks that promise. Code written for Rectangle then gives a wrong answer. The type checker accepts the program, because the signatures match. This is what Liskov and Wing mean when they say that the signature rules do not ensure behaviour.220
This code runs but gives a wrong answer on purpose.
class Rectangle:
def __init__(self, width: float, height: float) -> None:
self.width = width
self.height = height
def set_width(self, width: float) -> None:
self.width = width
def area(self) -> float:
return self.width * self.height
class Square(Rectangle):
def __init__(self, side: float) -> None:
super().__init__(side, side)
def set_width(self, width: float) -> None:
self.width = width
self.height = width
def stretch(shape: Rectangle) -> float:
shape.set_width(shape.width * 2)
return shape.area()
print(stretch(Rectangle(2, 3)))
print(stretch(Square(3)))
12
36
stretch expects the area to double, from 6 to 12 and from 9 to 18. The square gives 36. An immutable Square, or a common base Shape with no setters, avoids the problem.
Method parameters in TypeScript
TypeScript checks the parameters of methods bivariantly, also with strictFunctionTypes.3132 The object below declares handle with a Dog parameter, and the compiler accepts it as a Handler, whose method takes any Animal. A call with an Animal then fails at run time. The runner strips the types and does not run the type checker, so the block shows the run time failure.
This code raises TypeError, on purpose.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark(): string {
return "woof";
}
}
interface Handler {
handle(animal: Animal): string;
}
const dogsOnly: Handler = {
handle(dog: Dog): string {
return dog.bark();
},
};
console.log(dogsOnly.handle(new Animal()));
The program stops with TypeError: dog.bark is not a function. If Handler declares a property of function type, handle: (animal: Animal) => string, then strictFunctionTypes rejects the assignment.32
Slicing in C++
A C++ function that takes a base class by value copies only the base part of the argument. The copy is a real base object, so a virtual call on it uses the base class version.
This code runs but gives a wrong answer on purpose.
#include <iostream>
#include <string>
struct Shape {
virtual ~Shape() = default;
virtual std::string name() const { return "shape"; }
};
struct Circle : Shape {
std::string name() const override { return "circle"; }
};
void by_value(Shape shape) { std::cout << shape.name() << "\n"; }
void by_reference(const Shape& shape) { std::cout << shape.name() << "\n"; }
int main() {
Circle circle;
by_value(circle);
by_reference(circle);
}
shape
circle
Take a polymorphic argument by reference or by pointer.
Cost
- Dynamic dispatch. A virtual call loads the table pointer from the object and the address from the table, and then calls the address.16 A Go interface call goes through the interface table in the same way.18
- Pointer conversion. A conversion to the primary base class costs nothing under the Itanium ABI, because the base is at offset zero. A conversion to another base adds an offset.1415
- The array store check. Covariant arrays in Java and C# need a type check on each store into an array of references.242526 Arrays of primitive types and value types have no such check.
- Checked casts. A cast from a supertype to a subtype, such as
(Square) shapein Java, checks the dynamic type at run time. The JVM uses the same rules for the store check ofaastoreas for the cast instructioncheckcast.25 - Structural checks. Structural subtyping in TypeScript costs nothing at run time, because the types are erased. In Python, the documentation warns that an
isinstancecheck against a runtime-checkable protocol can be slow compared with a check against an ordinary class.11
History
- Simula 67. According to Cardelli, inheritance and object-oriented programming first appeared in Simula 67. Objects of a class could appear wherever objects of a superclass were expected.37
- 1987. Barbara Liskov gave the keynote "Data abstraction and hierarchy" at OOPSLA '87. It defined a subtype by the substitution property and separated type hierarchy from implementation hierarchy.14
- 1988. Luca Cardelli published "A semantics of multiple inheritance" in Information and Computation. It gave the subtyping rules for records and for function types.3
- 1994. Barbara Liskov and Jeannette Wing published "A behavioral notion of subtyping". It defined subtypes by the properties that a program can prove about the supertype, including invariants and history constraints.220
- TypeScript 2.6. This release added the
strictFunctionTypesoption, which checks the parameters of function types contravariantly but not those of methods.31
References
- Barbara Liskov, Data abstraction and hierarchy, keynote address, OOPSLA '87 Addendum to the Proceedings, October 1987, 3.3 Type Hierarchy (the substitution property; subtype and supertype are semantic, subclass and superclass are linguistic)
- Barbara H. Liskov and Jeannette M. Wing, A behavioral notion of subtyping, ACM Transactions on Programming Languages and Systems 16(6), 1994, 1 Introduction (the Subtype Requirement; the signature rules alone do not make a stack a subtype of a queue)
- Luca Cardelli, A semantics of multiple inheritance, Information and Computation 76(2-3), 1988, 3 Records (Rule2 for record types, Rule3 subsumption, Rule6 for function types)
- Barbara Liskov, Data abstraction and hierarchy, keynote address, OOPSLA '87 Addendum to the Proceedings, October 1987, 3.1 Inheritance and 3.2 Implementation Hierarchy (subclasses that violate encapsulation; inheritance used only to implement a type)
- The Java Language Specification, Java SE 25 Edition, 4.10.2 Subtyping among Class and Interface Types
- Barbara Liskov, Data abstraction and hierarchy, keynote address, OOPSLA '87 Addendum to the Proceedings, October 1987, 5.1 Polymorphism (the grouping approach, in which a module accepts any type with the needed operations)
- TypeScript Handbook, Type Compatibility, the introduction (structural subtyping) and Starting out
- The Go Programming Language Specification, Interface types and Implementing an interface
- The Go Programming Language Specification, Assignability (a value x is assignable to an interface type T if x implements T)
- PEP 544: Protocols: Structural subtyping (static duck typing), Abstract and Nominal vs structural subtyping
- The Python Standard Library, typing, Python 3.14, typing.Protocol (protocol classes with runtime_checkable check only the presence of the attributes) and the note on runtime_checkable (isinstance checks can be slow)
- The Python Standard Library, abc, Python 3.14, ABCMeta.register (virtual subclasses)
- ECMAScript 2026 Language Specification, 7.3.21 OrdinaryHasInstance (the walk along the prototype chain)
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [conv.ptr], paragraph 3
- Itanium C++ ABI, 2.4 Non-POD Class Types (the primary base is allocated first; Allocation of Members Other Than Virtual Bases)
- Itanium C++ ABI, 2.5.1 General (a virtual table is used to dispatch virtual functions)
- The Go Programming Language Specification, Variables (the static type and the dynamic type of a variable of interface type)
- Russ Cox, Go Data Structures, Interfaces, 1 December 2009, Interface Values (a two-word pair of an itable pointer and a data pointer)
- ISO/IEC 9899:201x, Committee Draft N1570 (C11), 6.7.2.1 Structure and union specifiers, paragraph 15
- Barbara H. Liskov and Jeannette M. Wing, A behavioral notion of subtyping, ACM Transactions on Programming Languages and Systems 16(6), 1994, 5.2, Fig. 4 (the definition of the subtype relation, with the signature rules, the methods rule and the properties rule)
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [class.virtual], paragraph 8 (covariant return types)
- The Java Language Specification, Java SE 25 Edition, 8.4.5 Method Result (return-type-substitutable)
- The Java Language Specification, Java SE 25 Edition, 4.10.3 Subtyping among Array Types
- The Java Language Specification, Java SE 25 Edition, 10.5 Array Store Exception
- The Java Virtual Machine Specification, Java SE 25 Edition, 6.5 aastore (Run-time Exceptions)
- C# language specification, Arrays, 17.6 Array covariance
- Kotlin documentation, Generics, in, out, where, Declaration-site variance and Type projections (Array<T> is invariant in T)
- Kotlin standard library API, kotlin.collections.List, the declaration interface List<out E> and its description (read-only access)
- C# programming guide, Covariance and Contravariance, the first example (IEnumerable<string> assigned to IEnumerable<object>, Action<object> assigned to Action<string>)
- TypeScript Handbook, Type Compatibility, Function Parameter Bivariance
- TypeScript 2.6 release notes, Strict function types (methods are excluded)
- TSConfig Reference, Strict Function Types (the setting applies to function syntax, not to method syntax)
- The Rust Reference, Subtyping and Variance, [subtype.kinds] (subtyping is restricted to lifetimes)
- The Rust Reference, Subtyping and Variance, [subtyping.variance.builtin-types] (the variance table)
- PowerShell documentation, about_Classes_Inheritance, Short description and Long description (single inheritance from a base class)
- PostgreSQL 18 Documentation, 5.11 Inheritance (INHERITS, and the limitation for indexes and foreign keys)
- Luca Cardelli, A semantics of multiple inheritance, Information and Computation 76(2-3), 1988, 1 Introduction (inheritance first appeared in Simula 67)
- The Java Language Specification, Java SE 25 Edition, 4.10.1 Subtyping among Primitive Types
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag MRV58N Edit this page History Report an error Markdown