Programming Search⌘K

Conceptcore

Interfaces

Also called interface, protocol, trait, type class, abstract base class, pure abstract class, contract.

An interface is a named set of operations that a type promises to provide. Code written against it works with every type that keeps the promise.

Applies to
core-languages

Idea

An interface is a named set of operations. A type that implements the interface promises to provide each operation. Code that is written against the interface can then work with any such type. It does not need to know which type it has.

Java describes an interface as "a common supertype for otherwise unrelated classes". An interface has no instance variables, and a program cannot create an object of the interface itself.1 Other languages use other names for the same idea. Python has protocols, Rust has traits, Haskell has type classes, and C++ uses abstract classes.

In the program below, expired needs only one operation: the current time. The interface Clock names that operation. The program passes a fixed clock and the system clock, and expired treats them the same way.

public class Main {
    interface Clock {
        long millis();
    }

    static final class SystemClock implements Clock {
        public long millis() {
            return System.currentTimeMillis();
        }
    }

    record FixedClock(long millis) implements Clock {}

    static boolean expired(Clock clock, long deadline) {
        return clock.millis() > deadline;
    }

    public static void main(String[] args) {
        System.out.println(expired(new FixedClock(100), 50));
        System.out.println(expired(new FixedClock(10), 50));
        System.out.println(expired(new SystemClock(), 50));
    }
}
Output
true
false
true

The record FixedClock gets a method millis() from its component, and that method implements the interface. A test can use a fixed clock, and the real program can use the system clock. This is the main use of an interface: it separates the code that needs an operation from the code that provides it. The Strategy pattern is this idea used as a design pattern.

How it works

An interface involves three things. The declaration lists the operations. An implementation provides them for one type. A call site uses them through the interface. Languages differ in each part.

Declaring that a type implements an interface

  • Nominal. The type names the interface. In Java a class lists it in an implements clause. Unless the class is abstract, it must implement every abstract method of the interface, or the program does not compile.3 The first edition of the Java specification states the rule plainly. It is not sufficient that a class happens to have all the methods. The class must be declared to implement the interface.7 C#, Kotlin and C++ work the same way.833
  • Structural. The type implements the interface when it has the operations, and nothing names the interface. In Go, a type implements an interface when its method set contains the methods of the interface.11 TypeScript compares types by their members.25 Python protocols give the same rule to a static type checker.21
  • Separate instances. In Rust, an impl Shape for Square block implements a trait for a type. The block is separate from the type. So a crate can implement its own trait for a type from another crate, or a trait from another crate for its own type. The orphan rule forbids the remaining case: the trait or at least one of the types must be local to the crate.18 Haskell instance declarations work in the same way.20

The Subtyping node compares nominal and structural relations in more detail.

Default methods

An interface can also give a body to some operations. A type that implements the interface gets the body unless it provides its own.

Java added default methods in Java SE 8. A default method is an instance method that is declared in an interface with the default modifier.4 The reason was library evolution. Without default methods, an added method in an interface breaks every class that implements the interface. JSR 335 listed "virtual extension methods", so that interfaces could gain methods "after the fact" without breaking existing implementation classes.5 The Java SE 8 notes say that default methods keep binary compatibility with code written for older versions.6

C# 8.0 added default interface members in September 2019.10 The proposal calls them virtual extension methods, like Java's default methods.9 Rust traits and Haskell classes can give default bodies too.3820 In C++, a non-virtual member function of an abstract class plays the same part. The describe function in the C++ example calls the pure virtual functions of its own class.

Static dispatch

A call through an interface needs the code of the right implementation. When the compiler knows the concrete type at the call site, it can call that code directly. This is static dispatch.

Rust does this for a generic function such as fn total<T: Shape>(items: &[T]). The compiler generates a separate copy of the function for each concrete type that the program uses. The Rust book calls this monomorphization. Each copy calls the method directly, and the compiler can inline it.19 C++ templates work the same way. A C++20 concept is "a template that defines constraints on its template arguments".30 It checks the type at compile time and gives no run-time dispatch.

Haskell takes a third path. Wadler and Blott showed how to translate a program with type classes into a program without them. Each instance becomes a record of functions, which they call a method dictionary. A function with a class constraint gets an extra parameter, the dictionary, and calls the operations through it. In their example, the class Num becomes a data type NumD with one field for each operation.2

Dynamic dispatch

When the compiler does not know the concrete type, the program must find the code at run time. All the common designs use a table of function pointers. They differ in where the table pointer lives.

  • A table pointer in the object. A C++ object of a class with virtual functions holds a pointer to a virtual table. A call loads the table pointer, loads the function address from the table, and calls it.31 A Java call through an interface compiles to the instruction invokeinterface. The JVM selects the method from the class of the object.32 The JVM specification defines which method is selected but not the data structure that finds it.
  • A table pointer next to the object. A Rust trait object &dyn Shape is a fat pointer. It holds a pointer to the data and a pointer to a vtable for the concrete type.16 The Rust example prints the sizes: 8 bytes for &Square and 16 bytes for &dyn Shape on a 64-bit target. A Go interface value is also two words. Russ Cox describes them as a pointer to an interface table, or itable, and a pointer to the data. Because Go types do not declare their interfaces, the runtime computes each itable when it first needs it, and caches it.15
  • No table. Python and JavaScript look up the method by name in the object and its class at each call. Cox contrasts this with the tables that C++ and Java prepare statically.15

C has no interfaces, but the same design is a common idiom. A struct of function pointers is the interface, and one constant instance of it for each type is the implementation. The C example pairs a pointer to such a table with a pointer to the data. A Go interface value has the same layout.

Dynamic dispatch lets one container hold values of many types. Static dispatch gives faster calls but needs one type per instantiation. The Rust example shows both forms of the same function.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptIdiom
TypeScriptNative
GoNative
RustNative
KotlinNativeA class or object implements one or more interfaces, and an interface can declare abstract methods, methods with bodies and abstract properties, but no state; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query has no user-defined types with operations.
BashDoes not applyBash has no types and no methods, only strings and arrays of strings. Alternative: A naming convention, where each "implementation" defines functions with the same names, and the script sources one file or another.
PowerShellNativeA PowerShell class can implement .NET interfaces such as System.IComparable, and a class that does not implement an interface that it names gives a parse error; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no types.
CSSDoes not applyStyle rules have no types.
Regular expressionsDoes not applyA pattern has no types.

The example files show interfaces in each language. The table gives the verdict for each tier 1 language.

Language Verdict Form
Python native abstract base classes in abc (nominal); typing.Protocol (structural, for a type checker)2223
JavaScript idiom no declaration; an object conforms when it has the properties, as with the iterable interface28
TypeScript native interface, compared by structure; erased before the program runs2526
Java native interface and implements, with default and static methods14
C idiom a struct of function pointers, with one constant table for each type
C++ native abstract classes with pure virtual functions; C++20 concepts for compile-time constraints2930
C# native interface, with default members and static abstract members835
Go native structural; a type implements an interface through its method set1112
Rust native traits and impl Trait for Type; generics or dyn Trait1618
Kotlin native interface, with method bodies and abstract properties but no state33
PowerShell native classes can implement .NET interfaces34
Bash n/a no types or methods
SQL n/a no user-defined types with operations
Regex n/a a pattern has no types
HTML n/a markup has no types
CSS n/a style rules have no types

Kotlin interfaces can contain abstract methods and method implementations. Unlike abstract classes, they cannot store state.33 A PowerShell class can implement a .NET interface. Some operators depend on this: -lt and -gt work only on classes that implement System.IComparable.34

PythonGitHub
import math
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable


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

    def describe(self) -> str:
        return f"{type(self).__name__} {self.area():.2f}"


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

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


@runtime_checkable
class HasArea(Protocol):
    def area(self) -> float: ...


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

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


def total(items: list[HasArea]) -> float:
    return sum(item.area() for item in items)


print(Square(2).describe())
print(f"{total([Square(2), Circle(1)]):.2f}")
print(isinstance(Circle(1), HasArea), isinstance(Circle(1), Shape))
print(isinstance(Square(2), HasArea), isinstance(Square(2), Shape))
Output
Square 4.00
7.14
True False
True True
  • Verdict: native. The abc module gives nominal interfaces: a class names the ABC as a base class. typing.Protocol gives structural interfaces for a static type checker.
  • Shape has an abstract method area and a concrete method describe, which plays the part of a default method.
  • Circle does not name HasArea, but it has area, so a type checker accepts it in total. With runtime_checkable, isinstance checks only that the attribute is present.
  • Python does not check the types at run time. A call to a missing method fails with AttributeError when it runs.
#include <iostream>
#include <memory>
#include <string>
#include <type_traits>
#include <vector>

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
    virtual std::string name() const = 0;
    std::string describe() const { return name() + " " + std::to_string(area()); }
};

struct Square : Shape {
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
    std::string name() const override { return "square"; }
    double side;
};

struct Circle : Shape {
    explicit Circle(double r) : radius(r) {}
    double area() const override { return 3.141592653589793 * radius * radius; }
    std::string name() const override { return "circle"; }
    double radius;
};

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));
    for (const auto& shape : shapes) {
        std::cout << shape->describe() << "\n";
    }
    std::cout << std::is_abstract_v<Shape> << " " << std::is_abstract_v<Square> << "\n";
}
Output
square 4.000000
circle 3.141593
1 0
#include <concepts>
#include <iostream>
#include <vector>

template <typename T>
concept HasArea = requires(const T& t) {
    { t.area() } -> std::convertible_to<double>;
};

struct Square {
    double side;
    double area() const { return side * side; }
};

struct Rect {
    double w, h;
    double area() const { return w * h; }
};

template <HasArea T>
double total(const std::vector<T>& items) {
    double sum = 0;
    for (const T& item : items) {
        sum += item.area();
    }
    return sum;
}

static_assert(HasArea<Square>);
static_assert(!HasArea<int>);

int main() {
    std::cout << total(std::vector<Square>{{1}, {2}}) << "\n";
    std::cout << total(std::vector<Rect>{{2, 3}}) << "\n";
}
Output
5
6
  • Verdict: native. C++ has no interface keyword. A class with only pure virtual functions serves as an interface. A derived class must override them all before a program can create an object of it.
  • describe is an ordinary member function of the base. It calls the virtual functions, so it acts as a default method.
  • A concept states requirements on a template argument. Square and Rect derive from nothing, and total accepts both. The check happens at compile time, and each call to total is a separate instantiation with direct calls.
  • A concept gives no run-time dispatch. A std::vector<HasArea> does not exist. Mixed types in one container need a virtual base class or type erasure.
JavaGitHub
import java.util.List;

public class Main {
    interface Shape {
        double area();

        default String describe() {
            return String.format("%s %.2f", getClass().getSimpleName(), area());
        }

        static Shape unit() {
            return new Square(1);
        }
    }

    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;
        }

        @Override
        public String describe() {
            return "circle of radius " + radius;
        }
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Square(2), new Circle(1), Shape.unit());
        for (Shape shape : shapes) {
            System.out.println(shape.describe());
        }
        System.out.println(Shape.class.isInterface());
        System.out.println(List.of(Square.class.getInterfaces()));
    }
}
Output
Square 4.00
circle of radius 1.0
Square 1.00
true
[interface Main$Shape]
  • Verdict: native. A class or record names its interfaces in an implements clause. The relation is nominal: a class with the right methods and no implements clause is not a Shape.
  • describe is a default method. Square inherits it, and Circle overrides it. Default methods came with Java SE 8.
  • unit is a static method of the interface. A caller writes Shape.unit().
  • The call shape.describe() compiles to the JVM instruction invokeinterface. The JVM selects the method from the class of the object at run time.
#include <stdio.h>

struct shape_ops {
    const char *name;
    double (*area)(const void *self);
};

struct shape {
    const struct shape_ops *ops;
    const void *self;
};

struct square {
    double side;
};

struct circle {
    double radius;
};

static double square_area(const void *self) {
    const struct square *s = self;
    return s->side * s->side;
}

static double circle_area(const void *self) {
    const struct circle *c = self;
    return 3.141592653589793 * c->radius * c->radius;
}

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

static double total(const struct shape *shapes, size_t n) {
    double sum = 0;
    for (size_t i = 0; i < n; i++) {
        sum += shapes[i].ops->area(shapes[i].self);
    }
    return sum;
}

int main(void) {
    struct square sq = {2.0};
    struct circle c = {1.0};
    struct shape shapes[] = {{&square_ops, &sq}, {&circle_ops, &c}};
    for (size_t i = 0; i < 2; i++) {
        printf("%s %.2f\n", shapes[i].ops->name, shapes[i].ops->area(shapes[i].self));
    }
    printf("%.2f\n", total(shapes, 2));
    return 0;
}
Output
square 4.00
circle 3.14
7.14
  • Verdict: idiom. C has no interfaces. A struct of function pointers is the interface, and one constant instance of it for each type is the implementation.
  • struct shape is a pair of an operations pointer and a data pointer. It has the same shape as a Go interface value or a Rust &dyn Trait.
  • The compiler does not check that self points to the type that the operations expect. A wrong pair gives undefined behaviour, so code builds each pair in one place.
IShape[] shapes = { new Square(2), new Circle(1) };
foreach (IShape shape in shapes)
{
    Console.WriteLine(shape.Describe());
}

Console.WriteLine(Sum(new[] { new Money(150), new Money(275) }));
Console.WriteLine(typeof(Square).GetInterfaces()[0].Name);

static T Sum<T>(T[] items) where T : IAddable<T>
{
    T total = T.Zero;
    foreach (T item in items)
    {
        total = total + item;
    }
    return total;
}

interface IShape
{
    double Area();
    string Describe() => $"{GetType().Name} {Area():F2}";
}

interface IAddable<T> where T : IAddable<T>
{
    static abstract T Zero { get; }
    static abstract T operator +(T left, T right);
}

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

class Circle(double radius) : IShape
{
    public double Area() => Math.PI * radius * radius;
    public string Describe() => $"circle of radius {radius}";
}

readonly record struct Money(long Cents) : IAddable<Money>
{
    public static Money Zero => new(0);
    public static Money operator +(Money left, Money right) => new(left.Cents + right.Cents);
}
Output
Square 4.00
circle of radius 1
Money { Cents = 425 }
IShape
  • Verdict: native. A class, struct or record lists its interfaces after the colon. The relation is nominal.
  • Describe in IShape has a body, so it is a default interface member. Square uses it. Circle declares its own public Describe, which implements the member.
  • IAddable<T> has static abstract members. Sum calls T.Zero and + on a type parameter, and the compiler binds them for each type argument.
  • A class does not inherit the default members of its interfaces. The Pitfalls section of the node shows the compile error.
JavaScriptGitHub
class Countdown {
  constructor(start) {
    this.start = start;
  }

  [Symbol.iterator]() {
    let n = this.start;
    return {
      next: () => (n > 0 ? { value: n--, done: false } : { value: undefined, done: true }),
    };
  }
}

console.log([...new Countdown(3)]);
for (const n of new Countdown(2)) {
  console.log(n);
}

function isIterable(value) {
  return value != null && typeof value[Symbol.iterator] === "function";
}

console.log(isIterable(new Countdown(1)), isIterable([1]), isIterable({}));

const plain = { start: 3 };
try {
  console.log([...plain]);
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
Output
[ 3, 2, 1 ]
2
1
true true false
TypeError: plain is not iterable
  • Verdict: idiom. JavaScript has no interface declaration. An object conforms to a protocol when it has the right properties, and code checks them at run time if it checks at all.
  • The language specification itself uses this idea. The iterable interface is the method at the key Symbol.iterator. Countdown names no interface, but spread syntax and for...of accept it.
  • An object without the method fails only when it is used, with a TypeError.
TypeScriptGitHub
interface Shape {
  readonly name: string;
  area(): number;
}

class Square implements Shape {
  readonly name = "square";
  side: number;
  constructor(side: number) {
    this.side = side;
  }
  area(): number {
    return this.side * this.side;
  }
}

class Circle {
  readonly name = "circle";
  radius: number;
  constructor(radius: number) {
    this.radius = radius;
  }
  area(): number {
    return Math.PI * this.radius * this.radius;
  }
}

function describe(shape: Shape): string {
  return `${shape.name} ${shape.area().toFixed(2)}`;
}

const triangle: Shape = { name: "triangle", area: () => 6 };

for (const shape of [new Square(2), new Circle(1), triangle]) {
  console.log(describe(shape));
}
Output
square 4.00
circle 3.14
triangle 6.00
interface Shape {
  area(): number;
}

function isShape(value: unknown): value is Shape {
  return typeof value === "object" && value !== null && typeof (value as Shape).area === "function";
}

const values: unknown[] = [{ area: () => 4 }, { side: 2 }, "square"];
for (const value of values) {
  console.log(isShape(value) ? value.area() : "not a shape");
}
Output
4
not a shape
not a shape
  • Verdict: native. TypeScript compares interfaces by structure. Circle and the object literal have no implements clause, and describe accepts them.
  • An implements clause only asks the compiler to check the class. It does not change the type of the class.
  • The types are erased when the program runs. To test for an interface at run time, write a type predicate such as isShape, which checks the members.
package main

import (
	"fmt"
	"math"
	"strings"
)

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 }

var _ Shape = Square{}
var _ Shape = Circle{}

type Counter struct{ n int }

func (c *Counter) Add() { c.n++ }

func (c *Counter) String() string { return fmt.Sprintf("count %d", c.n) }

var _ fmt.Stringer = (*Counter)(nil)

func main() {
	for _, s := range []Shape{Square{2}, Circle{1}} {
		fmt.Printf("%T %.2f\n", s, s.Area())
	}

	var c Counter
	c.Add()
	c.Add()
	fmt.Println(c)
	fmt.Println(&c)

	var b strings.Builder
	fmt.Fprintf(&b, "%d shapes", 2)
	fmt.Println(b.String())
}
Output
main.Square 4.00
main.Circle 3.14
{2}
count 2
2 shapes
  • Verdict: native. A type implements an interface when its method set contains the methods of the interface. No declaration names the interface.
  • The lines var _ Shape = Square{} and var _ fmt.Stringer = (*Counter)(nil) are checks at compile time. They make the build fail if the type stops implementing the interface.
  • String has a pointer receiver, so it is in the method set of *Counter but not in the method set of Counter. fmt.Println(c) does not see a Stringer and prints the fields. fmt.Println(&c) calls String.
  • strings.Builder never mentions io.Writer. It has a Write method, so fmt.Fprintf accepts a pointer to it.
RustGitHub
use std::fmt;
use std::mem::size_of;

trait Shape {
    fn area(&self) -> f64;

    fn describe(&self) -> String {
        format!("area {:.2}", self.area())
    }
}

struct Square {
    side: f64,
}

struct Circle {
    radius: f64,
}

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

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

    fn describe(&self) -> String {
        format!("circle of radius {}", self.radius)
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "square of side {}", self.side)
    }
}

fn total_static<T: Shape>(items: &[T]) -> f64 {
    items.iter().map(|s| s.area()).sum()
}

fn total_dynamic(items: &[Box<dyn Shape>]) -> f64 {
    items.iter().map(|s| s.area()).sum()
}

fn main() {
    let squares = [Square { side: 1.0 }, Square { side: 2.0 }];
    println!("{:.2}", total_static(&squares));
    println!("{}", squares[1]);

    let mixed: Vec<Box<dyn Shape>> = vec![Box::new(Square { side: 2.0 }), Box::new(Circle { radius: 1.0 })];
    for s in &mixed {
        println!("{}", s.describe());
    }
    println!("{:.2}", total_dynamic(&mixed));

    println!("{} {}", size_of::<&Square>(), size_of::<&dyn Shape>());
}
Output
5.00
square of side 2
area 4.00
circle of radius 1
7.14
8 16
  • Verdict: native. A trait declares methods, and impl Shape for Square implements them for one type. The impl block is separate from the type, so a crate can implement its own trait for a type from another crate, such as f64.
  • total_static is generic. The compiler makes one copy of it for each type T that the program uses, and each copy calls area directly. This is static dispatch.
  • total_dynamic takes trait objects. A call to area goes through the vtable of each object. This is dynamic dispatch.
  • On a 64-bit target, &Square is one pointer of 8 bytes. &dyn Shape is 16 bytes: a pointer to the data and a pointer to the vtable.
  • Abstract classes. An abstract class can mix abstract methods with fields and constructors. C++ has no separate interface construct. The standard notes that an abstract class can be used to define an interface whose implementations are in derived classes.29 The Template Method pattern uses an abstract class with a fixed algorithm and abstract steps.
  • Static members. C# interfaces can declare static abstract members, including operators. A generic method can then call T.Zero or + on a type parameter.35 This is close to a Haskell type class, where Num declares (+) for a type.20 The C# example shows it.
  • Generic bounds. A bound such as <T extends Comparable<T>> or T: Shape combines an interface with Generics. The bound says which operations the generic code may use.
  • Closed sets of types. An interface is open: any type can implement it later. When the set of variants is fixed, a Sum types declaration lets the compiler check that a match handles each case.
  • Hiding the concrete type. A caller that holds a value through an interface or a trait object does not see its concrete type. Type erasure covers the ways that languages remove or hide type information.
  • Duck typing. Python and JavaScript call a method if the object has it. No declaration is needed, and a missing method fails at run time. The ECMAScript specification uses this model for its own interfaces. It defines an interface as a set of property keys, and says that an interface is not represented by a distinct object.28 Static and dynamic typing explains the difference.

Pitfalls

A class that misses a method

A Java class that implements an interface must implement all its abstract methods, unless the class is abstract.3

This code does not compile, on purpose.

public class Main {
    interface Shape {
        double area();
        double perimeter();
    }

    static class Square implements Shape {
        public double area() {
            return 4;
        }
    }

    public static void main(String[] args) {
        System.out.println(new Square().area());
    }
}

javac reports that Square is not abstract and does not override the abstract method perimeter() in Shape. Add the method, or give it a default body in the interface.

A pointer receiver in Go

In Go, a method with a pointer receiver is in the method set of *T but not in the method set of T.12 So the value Counter{} does not implement fmt.Stringer, although &Counter{} does.

This code does not compile, on purpose.

package main

import "fmt"

type Counter struct{ n int }

func (c *Counter) String() string { return fmt.Sprintf("count %d", c.n) }

var _ fmt.Stringer = Counter{}

func main() {
	fmt.Println(&Counter{})
}

The compiler says that Counter does not implement fmt.Stringer, because method String has a pointer receiver. A type with a missing method gives the same kind of error. The line var _ fmt.Stringer = (*Counter)(nil) is the check that the Go FAQ recommends.13

Creating an object of an abstract class

In C++, no objects of an abstract class can be created, except as subobjects of a derived class. A class is abstract when it has at least one pure virtual function, or when a pure virtual function is not overridden.29

This code does not compile, on purpose.

#include <iostream>

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

struct Square : Shape {
    double area() const override { return 4; }
};

int main() {
    Square square;
    std::cout << square.area() << "\n";
}

Square does not override perimeter, so it is still abstract, and Square square; does not compile.

A missing abstract method in Python

Python checks an abstract base class when the program creates an object, not when it defines the class. A class with the metaclass ABCMeta cannot be instantiated unless all its abstract methods are overridden.22

This code raises TypeError, on purpose.

from abc import ABC, abstractmethod


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

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


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

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


print("class defined")
print(Square(2).area())

The class definition succeeds, and the first line prints. The call Square(2) raises TypeError, because perimeter has no implementation.

A nil pointer inside a Go interface

A Go interface value holds a type and a value. It is nil only when both are unset. If a function stores a nil *MyError in a result of type error, the result has a type, so it is not nil.14

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

type MyError struct{}

func (e *MyError) Error() string { return "failed" }

func check(fail bool) error {
	var p *MyError
	if fail {
		p = &MyError{}
	}
	return p
}

func main() {
	err := check(false)
	fmt.Println(err == nil)
	fmt.Printf("%T\n", err)
}
Output
false
*main.MyError

The caller expects true, but the result is false. The interface holds the type *main.MyError and a nil pointer. Return a literal nil for success, as the FAQ advises.

package main

import "fmt"

type MyError struct{}

func (e *MyError) Error() string { return "failed" }

func check(fail bool) error {
	if fail {
		return &MyError{}
	}
	return nil
}

func main() {
	fmt.Println(check(false) == nil)
	fmt.Println(check(true))
}
Output
true
failed

A trait that cannot be a trait object

A Rust trait can be used as dyn Trait only if it is dyn compatible. Each method must be dispatchable through a vtable, or must be explicitly excluded with where Self: Sized. A dispatchable method must not use Self except in the receiver.17 The method scaled below returns Self, so the vtable cannot hold it.

This code does not compile, on purpose.

trait Shape {
    fn area(&self) -> f64;
    fn scaled(&self, k: f64) -> Self;
}

struct Square {
    side: f64,
}

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

    fn scaled(&self, k: f64) -> Self {
        Square { side: self.side * k }
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square { side: 2.0 })];
    println!("{}", shapes[0].area());
}

rustc rejects the program with error E0038: the trait Shape is not dyn compatible. Write fn scaled(&self, k: f64) -> Self where Self: Sized;. The method is then not available on a trait object, but the rest of the trait is.

A default member called through the class in C#

A C# class does not inherit the members of its interfaces. A default member is therefore not a member of the class.9

This code does not compile, on purpose.

var square = new Square(2);
Console.WriteLine(square.Describe());

interface IShape
{
    double Area();
    string Describe() => $"area {Area():F2}";
}

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

The compiler reports that Square does not contain a definition for Describe. Call the member through the interface: IShape shape = square; and then shape.Describe().

Testing for a TypeScript interface at run time

TypeScript erases interfaces before the program runs.26 An implements clause only asks the compiler to check the class.24 So no value named Shape exists at run time. The runner here only strips the types, so the program fails when the line runs.

This code raises ReferenceError, on purpose.

interface Shape {
  area(): number;
}

const value: unknown = { area: () => 4 };
console.log("checking");
console.log(value instanceof Shape);

The program prints checking and then stops with ReferenceError: Shape is not defined. Check the members instead, with a type predicate such as isShape in the TypeScript example.27

Cost

  • Static dispatch. A monomorphized call is a direct call, which the compiler can inline.19 Each concrete type gets its own copy of the generic function, so the program has more machine code.
  • Dynamic dispatch. A call through a vtable or an itable is an indirect call through a table. It prevents inlining. The Rust book names this run-time cost.19
  • Fat pointers. A Rust &dyn Trait and a Go interface value are two words, not one.1615 A C++ object of a class with virtual functions pays instead with a table pointer inside the object.31
  • Itable construction. Go computes the itable for a pair of interface and concrete type at run time, when the pair first meets. It caches the result.15
  • Run-time checks. An isinstance check against a runtime-checkable protocol in Python looks for each attribute.23

History

  • 1989. Philip Wadler and Stephen Blott presented type classes at POPL. The work grew out of the design of Haskell. They gave a translation into dictionary passing.2
  • 1996. The first edition of the Java Language Specification defined interfaces as types separate from classes. A class had to declare the interfaces that it implemented.7
  • January 2002. C# 1.0 was released with interfaces.10
  • March 2012. Go 1 was released. Its interfaces are structural, and types implement them without a declaration.3613
  • March 2014. The Final Release of JSR 335 was published. The JSR covered lambda expressions and virtual extension methods, which Java SE 8 calls default methods.56
  • 2017. PEP 544 was created in March 2017. It added protocols to Python 3.8 for structural subtyping in type checkers.21
  • September 2019. C# 8.0 added default interface members.10

References

  1. The Java Language Specification, Java SE 25 Edition, Chapter 9 Interfaces, introduction (a common supertype for otherwise unrelated classes; no instance variables; not directly instantiated)
  2. Philip Wadler and Stephen Blott, How to make ad-hoc polymorphism less ad hoc, POPL 1989, Sections 3 and 4, Figure 2 (type classes and their translation into code that passes method dictionaries)
  3. The Java Language Specification, Java SE 25 Edition, 8.1.5 Superinterfaces (unless the class is abstract, it must implement the abstract methods of each direct superinterface) and 8.1.1.1 abstract Classes
  4. The Java Language Specification, Java SE 25 Edition, 9.4 Method Declarations (default methods; a method without private, default or static is implicitly abstract) and 9.4.3 Interface Method Body
  5. JSR 335, Lambda Expressions for the Java Programming Language, Section 2.1 (Virtual Extension Methods, so that interfaces can gain methods without breaking existing implementation classes) and the Final Release of 04 March 2014
  6. Java Programming Language Enhancements, Enhancements in Java SE 8 (default methods and binary compatibility; static methods in interfaces)
  7. James Gosling, Bill Joy and Guy Steele, The Java Language Specification, first edition (Java 1.0), Sun Microsystems, 1996, Chapter 9 Interfaces, introduction (a class must be declared to implement the interface; implementing all the methods is not sufficient)
  8. C# language reference, interface keyword, the introduction (an interface defines a contract) and Default interface members
  9. C# language proposal, default interface methods (C# 8.0), Summary (virtual extension methods, like Java's default methods) and Concrete methods in interfaces (a class does not inherit members from its interfaces)
  10. The history of C#, C# version 8.0 (released September 2019; default interface members) and C# version 1.0 (released January 2002; interfaces)
  11. The Go Programming Language Specification, Interface types, Basic interfaces and Implementing an interface
  12. The Go Programming Language Specification, Method sets (the method set of *T includes the methods with receiver *T or T; the method set of T only those with receiver T)
  13. Go Frequently Asked Questions, How can I guarantee my type satisfies an interface? (var _ T = (*MyType)(nil)) and Why doesn't Go have "implements" declarations?
  14. Go Frequently Asked Questions, Why is my nil error value not equal to nil? (an interface value is a type and a value, and is nil only when both are unset)
  15. Russ Cox, Go Data Structures, Interfaces, 1 December 2009, Interface Values and Computing the Itable (a two-word pair of an itable pointer and a data pointer; the runtime computes the itable and caches it)
  16. The Rust Reference, Trait objects, [type.trait-object.intro] and [type.trait-object.unsized] (a pointer to a trait object holds a data pointer and a vtable pointer; calls use virtual dispatch)
  17. The Rust Reference, Traits, [items.traits.dyn-compatible] and [items.traits.dyn-compatible.associated-functions] (dispatchable and explicitly non-dispatchable functions)
  18. The Rust Reference, Implementations, [items.impl.trait.coherence.intro] and [items.impl.trait.orphan-rule.intro] (the trait or one of the types must be local to the crate)
  19. The Rust Programming Language, Using Trait Objects to Abstract over Shared Behavior, Performing Dynamic Dispatch (monomorphization gives static dispatch; trait objects give dynamic dispatch, with a cost at run time and no inlining)
  20. Haskell 2010 Language Report, 4.3 Type Classes and Overloading, 4.3.1 Class Declarations and 4.3.2 Instance Declarations
  21. PEP 544: Protocols: Structural subtyping (static duck typing), Header (Created 05-Mar-2017, Python-Version 3.8), Abstract, and Explicitly declaring implementation
  22. The Python Standard Library, abc, Python 3.14, abc (the module provides the infrastructure of PEP 3119) and abc.abstractmethod (a class with ABCMeta cannot be instantiated unless all abstract methods are overridden)
  23. The Python Standard Library, typing, Python 3.14, typing.Protocol and typing.runtime_checkable (the check looks only for the presence of the attributes)
  24. TypeScript Handbook, Classes, implements Clauses and Cautions (an implements clause is only a check and does not change the type of the class)
  25. TypeScript Handbook, Type Compatibility, the introduction (structural subtyping) and Starting out
  26. TypeScript Handbook, The Basics, Erased Types
  27. TypeScript Handbook, Narrowing, Using type predicates
  28. ECMAScript 2026 Language Specification, 27.1.1 Common Iteration Interfaces (an interface is a set of property keys; it is not represented by a distinct object) and 27.1.1.1 The Iterable Interface
  29. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [class.abstract], paragraphs 1, 2 and 4 (pure virtual functions; no objects of an abstract class except as subobjects)
  30. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [temp.concept], paragraph 1 (a concept is a template that defines constraints on its template arguments)
  31. Itanium C++ ABI, 2.5.1 General (a virtual table is used to dispatch virtual functions)
  32. The Java Virtual Machine Specification, Java SE 25 Edition, 6.5 invokeinterface, Description (a method is selected with respect to the class of objectref and the resolved method)
  33. Kotlin documentation, Interfaces, the introduction (interfaces can contain abstract methods and method implementations but cannot store state) and Implementing interfaces
  34. PowerShell documentation, about_Classes_Inheritance, Long description (a class that does not implement an interface that it inherits gives a parsing error) and Implementing interfaces
  35. C# language reference, interface keyword, Static abstract and virtual members
  36. Go release history, go1 (released 2012-03-28)
  37. The Rust Programming Language, Defining Shared Behavior with Traits, Implementing a Trait on a Type and Default Implementations

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/3W80ZN/text.yaml