Programming Search⌘K

Conceptcore

Inheritance

Also called inheritance, subclassing, derived class, base class, superclass, implementation inheritance, multiple inheritance, diamond problem.

Inheritance defines a class as an extension of another: the subclass gets the fields and methods of its base, adds its own, overrides some, and can usually stand in for the base.

Applies to
core-languages

Idea

Inheritance defines a new class as an extension of an existing one. The subclass, or derived class, gets the fields and methods of its base class, adds its own, and can replace some inherited methods with its own versions. A Checking account that inherits from Account needs to write only what is different about checking accounts. Inheritance also makes the subclass a subtype in most languages, so a Checking can go wherever an Account is expected. Simula 67 introduced it, and Smalltalk, C++, Java, C#, Python and JavaScript made it the main tool of object-oriented design. Go and Rust leave it out and use composition and interfaces instead.

class Account:
    def __init__(self, owner, balance=0):
        self.owner, self.balance = owner, balance

    def deposit(self, amount):
        self.balance += amount
        return self

    def describe(self):
        return f"{type(self).__name__} of {self.owner}: {self.balance}"


class Savings(Account):  # inherits __init__, deposit and describe
    rate = 0.02

    def add_interest(self):  # adds a method
        return self.deposit(round(self.balance * self.rate))


class Checking(Account):
    def __init__(self, owner, balance=0, overdraft=100):
        super().__init__(owner, balance)  # reuses the initializer of the base
        self.overdraft = overdraft

    def describe(self):  # overrides and extends a method
        return super().describe() + f" (overdraft {self.overdraft})"


accounts = [Savings("ana", 1000), Checking("bo", 50)]
accounts[0].add_interest()
for a in accounts:
    a.deposit(10)
    print(a.describe(), isinstance(a, Account))
print("deposit" in vars(Savings), "add_interest" in vars(Savings))
print([c.__name__ for c in Checking.__mro__])
Output
Savings of ana: 1030 True
Checking of bo: 60 (overdraft 100) True
False True
['Checking', 'Account', 'object']

Savings defines one method and inherits the rest: __init__, deposit and describe are not in its own dictionary, vars(Savings), but Python finds them in Account. Checking replaces __init__ and describe, and each replacement calls the version of the base with super(), so it extends the inherited code instead of copying it. Both kinds of account pass isinstance(a, Account), and the loop treats them alike. __mro__ lists the classes in which Python searches for a name, from the class itself to object.

How it works

What a subclass gets. A subclass object contains the fields of its base class, usually as a prefix of its own layout, so code compiled for the base finds them at the same offsets. Methods are found through the class: a dynamic language searches the class and then its bases, and a compiled language copies the method table of the base and changes the entries that the subclass overrides. The Python tutorial states the consequence for methods that call each other: "Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it."1 See dynamic dispatch.

Overriding, extending and constructing. An overriding method can call the method it replaces, with super() in Python, Java and JavaScript and base in C#, so that the subclass adds to the behavior instead of copying it. Constructors are not inherited in Java and C#, and a subclass constructor must first call a constructor of its base. The base part of the object is built first and the derived part second, and C++ destroys the parts in the reverse order. Access levels control what a subclass can see: private members stay in the base, and protected members are visible to subclasses but not to other code.

Two jobs in one mechanism. Inheritance does two different things. The Rust Book names them: "You would choose inheritance for two main reasons. One is for reuse of code", and "The other reason to use inheritance relates to the type system: to enable a child type to be used in the same places as the parent type."2 The C++ reference describes the second: "Public inheritance models the subtyping relationship of object-oriented programming: the derived class object IS-A base class object."3 The two jobs can disagree. A class can reuse the code of another class without being a valid substitute for it, and then code that expects the base breaks. See subtyping.

Multiple inheritance. C++, Python and Eiffel let a class have several base classes. When two bases share a base of their own, the class hierarchy forms a diamond, and the language must decide how many copies of the shared base the object holds and in which order to search the bases. C++ holds one copy for each path, unless the base is virtual: "For each distinct base class that is specified virtual, the most derived object contains only one base class subobject of that type".3 Python orders the bases with the C3 linearization, which, its documentation notes, "was invented by people working on Dylan".4 Java, C# and Kotlin allow one base class and any number of interfaces, which gives multiple inheritance of types without multiple inheritance of fields.

The case against inheritance. A subclass depends on details of its base: which methods call which, and in what order. A change to the base that keeps its documented behavior can still break a subclass, which is the fragile base class problem. The Rust Book gives the other risk: "Inheritance is often at risk of sharing more code than necessary. Subclasses shouldn't always share all characteristics of their parent class but will do so with inheritance."2 The Go FAQ explains why Go has no type inheritance: "Object-oriented programming, at least in the best-known languages, involves too much discussion of the relationships between types, relationships that often could be derived automatically."5 The usual alternative is composition: the new class holds an object of the old one and forwards the calls that it wants to expose.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript, with class extends, abstract classes and members, protected members, and the override keyword checked by the compiler.
GoAbsent
RustAbsent
KotlinNativeClasses are final by default and a class must be declared open to be extended; a class extends one class and any number of interfaces; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyThe standard has structured types with subtypes, but common engines do not implement them, and PostgreSQL table inheritance shares columns, not behavior.
BashDoes not applyBash has no classes or objects to inherit from.
PowerShellNativeA class can derive from one class, including .NET classes, and call the base constructor with base(); no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML elements inherit some CSS properties from their parents, but the language has no classes.
CSSDoes not applyInherited properties pass values from a parent element to its children, which is a different idea with the same name.
Regular expressionsDoes not applyA pattern has no types to derive from.
Language Verdict Mechanism
Python native class C(A, B); C3 method resolution order; super()
JavaScript native class ... extends over the prototype chain
TypeScript native as JavaScript; abstract and protected
Java native one superclass with extends; interfaces
Kotlin native open classes; one superclass; interfaces
C# native one base class; base(...); sealed
Go absent struct embedding promotes fields and methods
Rust absent default trait methods, supertraits, composition
C idiom the base struct as the first member
C++ native multiple inheritance; virtual bases; access levels
Bash n/a no classes
PowerShell native class Derived : Base
SQL n/a no classes in common engines
Regex n/a no types
HTML n/a no classes
CSS n/a property inheritance is a different idea

The languages fall into three groups. C++ and Python have multiple inheritance, and their example files show the diamond: two copies of the shared base or one virtual base in C++, and one order of the bases, computed by C3, in Python. Java, C#, Kotlin, TypeScript and JavaScript allow one base class, and add interfaces or mixins for the rest. Go and Rust have no inheritance: Go promotes the fields and methods of an embedded struct without making the outer type a subtype, and Rust shares code through default methods of traits and shares data through composition.

C has no classes, but the layout rule that a struct starts with its first member lets a struct play the role of a derived class, and large C code bases, such as the Linux kernel and CPython, are built on it.

PythonGitHub
class Base:
    def setup(self):
        return ["Base"]


class Logging(Base):
    def setup(self):
        return ["Logging"] + super().setup()


class Caching(Base):
    def setup(self):
        return ["Caching"] + super().setup()


class Service(Logging, Caching):  # a diamond: two paths lead to Base
    def setup(self):
        return ["Service"] + super().setup()


print(Service().setup())  # each class runs once, in the order of the MRO
print([c.__name__ for c in Service.__mro__])

try:
    class Broken(Base, Logging):  # Base before its own subclass: no consistent order
        pass
except TypeError as e:
    print("TypeError:", e)
Output
['Service', 'Logging', 'Caching', 'Base']
['Service', 'Logging', 'Caching', 'Base', 'object']
TypeError: Cannot create a consistent method resolution order (MRO) for bases Base, Logging

This code runs but gives a wrong answer on purpose.

class Plugin:
    hooks = []  # one list, stored in the class Plugin

    def add_hook(self, name):
        self.hooks.append(name)


class Audit(Plugin):
    pass


class Cache(Plugin):
    pass


Audit().add_hook("log")
Cache().add_hook("evict")
print(Audit.hooks, Cache.hooks)
Output
['log', 'evict'] ['log', 'evict']
  • Verdict: native. A class lists its base classes in parentheses, and Python supports multiple inheritance. The method resolution order, computed by the C3 algorithm, puts every class before its bases and keeps the order of the bases, so in the diamond each setup runs once and super() calls the next class in that order, not always the base class. A class list that has no such order, as in Broken, is a TypeError when the class is defined.
  • The wrong block puts a list in a class attribute. Subclasses inherit the attribute itself, not a copy, so Audit and Cache add to the one list of Plugin. Create mutable state in __init__, or give each subclass its own list in __init_subclass__.
#include <iostream>

struct Device { int id = 0; Device() { std::cout << "Device\n"; } };
struct Reader : virtual Device { Reader() { std::cout << "Reader\n"; } };
struct Writer : virtual Device { Writer() { std::cout << "Writer\n"; } };
struct Disk : Reader, Writer { Disk() { std::cout << "Disk\n"; } }; // one shared Device

struct A { int id = 0; };
struct B : A {};
struct C : A {};
struct D : B, C {}; // two copies of A

int main()
{
    Disk d;
    d.id = 7; // one Device subobject, so the name is not ambiguous
    std::cout << d.Reader::id << ' ' << d.Writer::id << '\n';

    D x;
    x.B::id = 1;
    x.C::id = 2;
    std::cout << x.B::id << ' ' << x.C::id << '\n';
}
Output
Device
Reader
Writer
Disk
7 7
1 2

This code does not compile, on purpose.

struct A { int id = 0; };
struct B : A {};
struct C : A {};
struct D : B, C {};

int main()
{
    D x;
    x.id = 3; // which A? B's or C's
}
  • Verdict: native. C++ has multiple inheritance, with public, protected and private bases. Public inheritance makes the derived class a subtype of the base, while private inheritance reuses the code of the base without the subtype relation. Constructors run from the base to the derived class, and destructors in the reverse order.
  • In a diamond, each ordinary base is a separate subobject, so D has two A parts, and the failing block cannot name x.id because it is ambiguous. A virtual base is shared: Disk has one Device, which the most derived class constructs once, before Reader and Writer.
JavaGitHub
public class Main {
    abstract static class Account {
        private int balance;             // private: subclasses go through deposit
        protected final String owner;    // protected: subclasses can read it

        Account(String owner) { this.owner = owner; }

        void deposit(int n) { balance += n; }
        int balance() { return balance; }
        abstract String kind();          // each subclass must supply it

        String describe() { return kind() + " of " + owner + ": " + balance; }
    }

    static class Savings extends Account {
        Savings(String owner) { super(owner); }
        String kind() { return "savings"; }
        void addInterest() { deposit(balance() / 50); }
    }

    static final class Checking extends Account { // final: no class can extend it
        private final int overdraft;

        Checking(String owner, int overdraft) {
            super(owner);                // the base constructor runs first
            this.overdraft = overdraft;
        }

        String kind() { return "checking"; }

        @Override
        String describe() { return super.describe() + " (overdraft " + overdraft + ")"; }
    }

    public static void main(String[] args) {
        Savings s = new Savings("ana");
        s.deposit(1000);
        s.addInterest();
        Account c = new Checking("bo", 100);
        c.deposit(50);
        for (Account a : new Account[] { s, c })
            System.out.println(a.describe());
        System.out.println(c.getClass().getSuperclass().getSimpleName());
    }
}
Output
savings of ana: 1020
checking of bo: 50 (overdraft 100)
Account

This code runs but gives a wrong answer on purpose.

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

public class Main {
    // A set that counts how many elements were ever added to it.
    static class CountingSet<E> extends HashSet<E> {
        int added = 0;

        @Override
        public boolean add(E e) {
            added++;
            return super.add(e);
        }

        @Override
        public boolean addAll(Collection<? extends E> c) {
            added += c.size();
            return super.addAll(c); // the inherited addAll calls add for each element
        }
    }

    public static void main(String[] args) {
        CountingSet<String> s = new CountingSet<>();
        s.addAll(List.of("a", "b", "c"));
        System.out.println(s.added);
    }
}
Output
6
  • Verdict: native. A class extends one class and inherits its fields and methods, and every class but Object has exactly one superclass. An abstract class can declare methods that each subclass must supply, protected members are visible to subclasses, and a final class cannot be extended. A constructor must call a constructor of the superclass first, with super(...) or implicitly. Interfaces give the multiple inheritance of types and of default methods, not of fields.
  • The wrong block is the fragile base class problem. CountingSet overrides add and addAll, but the inherited addAll of HashSet calls add for each element, so three elements count six times. The subclass depends on how its base calls its own methods, which the documentation of HashSet does not promise. Wrap a set in a new class and forward the calls instead of extending it.
#include <stdio.h>

struct account { const char *owner; int balance; };

/* The base comes first, so a pointer to a checking points to its account too. */
struct checking { struct account base; int overdraft; };

static void deposit(struct account *a, int n) { a->balance += n; }
static void describe(const struct account *a) { printf("account of %s: %d\n", a->owner, a->balance); }

static int can_withdraw(const struct checking *c, int n)
{
    return c->base.balance + c->overdraft >= n;
}

int main(void)
{
    struct checking c = { { "bo", 0 }, 100 };
    deposit(&c.base, 50);                    /* reuse the functions of the base */
    describe((const struct account *)&c);    /* valid: base is the first member */
    printf("withdraw 120: %d, withdraw 200: %d\n", can_withdraw(&c, 120), can_withdraw(&c, 200));
    return 0;
}
Output
account of bo: 50
withdraw 120: 1, withdraw 200: 0
  • Verdict: idiom. C has no classes, but a struct whose first member is another struct can stand in for a derived class. The C standard guarantees that a pointer to a struct, converted, points to its first member, so functions written for struct account work on a struct checking. With a table of function pointers in the base, this gives the whole object model of single inheritance. The Linux kernel, GLib and CPython's object headers use this layout.
  • The compiler does not check the casts. Casting a pointer to a struct that does not start with the base reads the wrong memory.
using System;

Account a = new Checking("bo", 100);
a.Deposit(50);
Console.WriteLine(a.Describe());
Console.WriteLine(typeof(Checking).BaseType!.Name);

class Account
{
    public string Owner { get; }
    public decimal Balance { get; private set; }

    public Account(string owner)
    {
        Owner = owner;
        Console.WriteLine("Account constructor");
    }

    public void Deposit(decimal n) => Balance += n;
    public virtual string Describe() => $"{GetType().Name} of {Owner}: {Balance}";
}

sealed class Checking : Account
{
    readonly decimal overdraft;

    public Checking(string owner, decimal overdraft) : base(owner) // the base constructor runs first
    {
        this.overdraft = overdraft;
        Console.WriteLine("Checking constructor");
    }

    public override string Describe() => base.Describe() + $" (overdraft {overdraft})";
}
Output
Account constructor
Checking constructor
Checking of bo: 50 (overdraft 100)
Account

This code does not compile, on purpose.

class Account { }

sealed class Checking : Account { }

class Premium : Checking { } // a sealed class cannot be a base class
  • Verdict: native. A class names one base class after a colon and inherits its members. The constructor calls a base constructor with : base(...), and the base constructor runs first, as the output shows. A member can be extended with base.Describe(), but only a virtual or abstract member can be overridden. private set lets subclasses read Balance but not set it.
  • sealed stops further inheritance, and the failing block is rejected with error CS0509. Sealing classes that are not designed for extension avoids the fragile base class problem, and it lets the runtime call their methods directly. A record can inherit from another record, and a struct cannot inherit from any type.
JavaScriptGitHub
class Account {
  #balance = 0; // private: a subclass cannot read it
  constructor(owner) { this.owner = owner; }
  deposit(n) { this.#balance += n; return this; }
  get balance() { return this.#balance; }
  describe() { return `${this.constructor.name} of ${this.owner}: ${this.balance}`; }
  static open(owner) { return new this(owner); } // static methods are inherited too
}

class Checking extends Account {
  constructor(owner, overdraft = 100) {
    super(owner); // must run before the constructor uses this
    this.overdraft = overdraft;
  }
  describe() { return `${super.describe()} (overdraft ${this.overdraft})`; }
}

const c = Checking.open("bo").deposit(50);
console.log(c.describe());
console.log(c instanceof Account,
  Object.getPrototypeOf(Checking.prototype) === Account.prototype,
  Object.getPrototypeOf(Checking) === Account);

class Stack extends Array { // a built-in class as the base
  peek() { return this.at(-1); }
}
const s = Stack.from([1, 2, 3]);
console.log(s.peek(), s.map((x) => x * 2) instanceof Stack);
Output
Checking of bo: 50 (overdraft 100)
true true true
3 true

This code raises ReferenceError, on purpose.

class Account {
  constructor(owner) { this.owner = owner; }
}

class Checking extends Account {
  constructor(owner) {
    this.overdraft = 100; // this does not exist before super() runs
    super(owner);
  }
}

console.log(new Checking("bo"));
  • Verdict: native. class Checking extends Account sets the prototype of Checking.prototype to Account.prototype, so instances find the methods of the base along the prototype chain, and it sets the prototype of Checking to Account, so static methods are inherited as well. new this(owner) in open creates an object of the class on which it is called. Built-in classes such as Array can be extended, and map on a Stack returns a Stack.
  • Private fields with # belong to the class that declares them, so Checking cannot read #balance and uses the getter. In the failing block, a derived constructor uses this before it calls super(), which is a ReferenceError, because the base constructor creates the object.
package main

import "fmt"

type Account struct {
	Owner   string
	balance int
}

func (a *Account) Deposit(n int)    { a.balance += n }
func (a *Account) Balance() int     { return a.balance }
func (a *Account) Describe() string { return fmt.Sprintf("account of %s: %d", a.Owner, a.balance) }

type Checking struct {
	Account   // embedded: its fields and methods are promoted to Checking
	Overdraft int
}

// Describe on Checking shadows the promoted method and calls it by name.
func (c *Checking) Describe() string {
	return fmt.Sprintf("%s (overdraft %d)", c.Account.Describe(), c.Overdraft)
}

type Describer interface{ Describe() string }

func main() {
	c := &Checking{Account: Account{Owner: "bo"}, Overdraft: 100}
	c.Deposit(50) // promoted from Account
	fmt.Println(c.Owner, c.Balance())
	for _, d := range []Describer{&c.Account, c} {
		fmt.Println(d.Describe())
	}
}
Output
bo 50
account of bo: 50
account of bo: 50 (overdraft 100)

This code does not compile, on purpose.

package main

type Account struct{ Owner string }

type Checking struct {
	Account
	Overdraft int
}

func main() {
	c := &Checking{Account{"bo"}, 100}
	var a *Account = c // a *Checking is not a *Account
	_ = a
}
  • Verdict: absent. Go has no inheritance. A struct can embed another type, and the fields and methods of the embedded type are promoted, so c.Deposit(50) and c.Owner work on a Checking. A method of the outer type with the same name shadows the promoted one, and it calls the inner one by its full name, c.Account.Describe().
  • Embedding is composition, not subtyping. The failing block assigns a *Checking to a *Account, which the compiler rejects, because the types are not related. Code that must accept both takes an interface, such as Describer, which both types satisfy.
RustGitHub
trait Account {
    fn owner(&self) -> &str;
    fn balance(&self) -> i64;
    fn describe(&self) -> String {
        // a default method: shared code that each type can override
        format!("account of {}: {}", self.owner(), self.balance())
    }
}

trait Interest: Account {
    // a supertrait: a type with Interest must also have Account
    fn rate_percent(&self) -> i64;
    fn interest(&self) -> i64 {
        self.balance() * self.rate_percent() / 100
    }
}

struct Basic {
    owner: String,
    balance: i64,
}

struct Savings {
    basic: Basic, // composition in place of a base class
    rate: i64,
}

impl Account for Basic {
    fn owner(&self) -> &str {
        &self.owner
    }
    fn balance(&self) -> i64 {
        self.balance
    }
}

impl Account for Savings {
    fn owner(&self) -> &str {
        self.basic.owner() // forwarding by hand
    }
    fn balance(&self) -> i64 {
        self.basic.balance()
    }
    fn describe(&self) -> String {
        format!("savings of {}: {}", self.owner(), self.balance())
    }
}

impl Interest for Savings {
    fn rate_percent(&self) -> i64 {
        self.rate
    }
}

fn main() {
    let b = Basic { owner: "bo".into(), balance: 50 };
    let s = Savings { basic: Basic { owner: "ana".into(), balance: 1000 }, rate: 2 };
    let all: Vec<&dyn Account> = vec![&b, &s];
    for a in &all {
        println!("{}", a.describe());
    }
    println!("interest {}", s.interest());
}
Output
account of bo: 50
savings of ana: 1000
interest 20
  • Verdict: absent. Rust has no inheritance of structs. The Rust Book gives the two reasons to use inheritance, the reuse of code and the use of a child type where the parent type is expected, and shows the replacements: default methods in traits give the reuse, and trait objects and generics give the substitution. A supertrait, trait Interest: Account, requires one trait for another, which is inheritance between interfaces, not between data.
  • Data is shared by composition: Savings holds a Basic and forwards to it. The forwarding is explicit code, which is the cost of this design, and it keeps each type in control of the methods that it exposes.
  • Interface inheritance. A class can inherit only the declarations of an interface and supply all the code itself, which gives the subtype relation without the reuse of code. See interfaces.
  • Mixins and traits. Small classes that add one feature, such as Python mixins, Ruby modules and Scala traits, are combined into a class without forming a deep hierarchy.
  • Prototype-based inheritance. In JavaScript, Self and Lua, an object inherits directly from another object, its prototype, and classes are a layer over this.
  • Composition and delegation. A class holds an object and forwards calls to it, which reuses code without making a subtype. See decorator pattern.
  • Abstract classes. A base class that declares methods without code, so that each subclass must supply them, as in the template method pattern.
  • Sealed and final classes. A class that no other class can extend, or a hierarchy whose subclasses are all known, which a compiler can check like a sum type. See sum types.
  • Embedding. Go and C put one struct inside another and reuse its fields and functions, without subtyping.
  • Object-oriented programming. Inheritance is one of the classic features of the paradigm, together with encapsulation and dynamic dispatch. See object-oriented programming.

Pitfalls

  • The fragile base class. A subclass that overrides one method can depend on how the base calls its own methods. The wrong block of the Java file counts each element twice for this reason. Prefer composition for classes that are not designed for extension, and seal or finalize such classes.
  • Inheritance for reuse alone. java.util.Stack extends Vector, so a stack accepts insertion in the middle, and Properties extends Hashtable, so it accepts keys that are not strings. Inherit only when the subclass is a valid substitute for the base.
  • Shared class attributes. In Python a mutable class attribute is inherited as the same object, as the wrong block of the Python file shows.
  • Forgetting the base constructor. In Python a subclass __init__ that does not call super().__init__() leaves the fields of the base unset. JavaScript rejects this before super(), as the failing block of the JavaScript file shows.
  • Diamonds. Two paths to the same base give two copies of it in C++, and an ambiguous name, as the failing block of the C++ file shows. Use virtual bases, or avoid diamonds of classes with data.
  • Deep hierarchies. Each level adds methods that a reader must find in another file. Keep hierarchies shallow, and put shared code in functions or components.
  • Calls to overridable methods from constructors. The override can run before the subclass has set its fields. See dynamic dispatch.

Cost

Inheritance of fields costs nothing at run time: the fields of the base are part of the object, at fixed offsets. Inheritance of methods costs what dynamic dispatch costs, an indirect call through a table, or a lookup along the chain of classes, which dynamic languages cache. Virtual bases in C++ add an indirection to find the shared base, and multiple inheritance adds a pointer adjustment when a pointer converts from the derived class to its second base. The larger costs are at build time and in maintenance: a change to a base class changes the layout or the behavior of every subclass, so in C++ all of them must be recompiled, and a library cannot add a field to a public base class without breaking binary compatibility.

History

Ole-Johan Dahl and Kristen Nygaard introduced subclasses in Simula 67, where a class could be prefixed by another class and inherit its attributes. Smalltalk, developed at Xerox PARC in the 1970s, built its whole library as one tree of classes with single inheritance. The Flavors system of the MIT Lisp Machine, around 1980, introduced mixins and multiple inheritance, Bertrand Meyer's Eiffel, from 1986, combined multiple inheritance with renaming, and C++ added multiple inheritance and virtual base classes in 1989.

Barbara Liskov's 1987 keynote "Data Abstraction and Hierarchy" stated the rule that a subtype must behave as its supertype, and the 1994 book Design Patterns by Gamma, Helm, Johnson and Vlissides advised to favor object composition over class inheritance. Java, in 1995, allowed one superclass and many interfaces. Kim Barrett and others described the C3 linearization for Dylan in 1996, and Python adopted it in 2003.4 Go, in 2009, and Rust, in 2015, left inheritance out of their designs.5

References

  1. The Python Tutorial, Classes, 9.5 Inheritance
  2. The Rust Programming Language, Characteristics of Object-Oriented Languages, Inheritance as a Type System and as Code Sharing
  3. Derived classes, cppreference.com, Virtual base classes; Public inheritance
  4. Michele Simionato, The Python 2.3 Method Resolution Order, Python documentation, The beginning
  5. Frequently Asked Questions (FAQ), The Go Programming Language, Why is there no type inheritance?

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