ZetCode

F# inheritance

last modified December 3, 2026

In this article we derive classes from other classes in F#.

Inheritance creates a new class from an existing one. The new derived class gets the members of the base class and can add its own or replace some of them. A value of a derived class can be used wherever the base class is expected. F# code uses inheritance less often than C# code; unions, records and interfaces cover many of the same needs. It is still the way to extend .NET classes and to share code between related objects.

A derived class

A derived class names its base class with inherit and passes it the constructor arguments it needs.

derived.fsx
type Animal(name: string) =
    member _.Name = name
    member _.Describe() = $"{name} is an animal"

type Dog(name: string, breed: string) =
    inherit Animal(name)
    member _.Breed = breed

let rex = Dog("Rex", "beagle")

printfn "%s" rex.Name
printfn "%s" rex.Breed
printfn "%s" (rex.Describe())

Dog inherits from Animal and adds a Breed property.

type Dog(name: string, breed: string) =
    inherit Animal(name)

The inherit line comes first in the class. It calls the primary constructor of Animal with the name; the breed is kept by Dog.

printfn "%s" (rex.Describe())

Name and Describe are defined in Animal, yet they can be called on a dog. A derived class has all the public members of its base.

λ dotnet fsi derived.fsx
Rex
beagle
Rex is an animal

Virtual members

A base class decides which of its members may be replaced. Such a virtual member is declared with abstract, which gives its type, and default, which gives the implementation used when a derived class does not replace it. A derived class replaces it with override.

virtual.fsx
type Animal(name: string) =
    member _.Name = name

    abstract Sound: unit -> string
    default _.Sound() = "..."

    member this.Speak() = $"{name} says {this.Sound()}"

type Dog(name) =
    inherit Animal(name)
    override _.Sound() = "woof"

type Cat(name) =
    inherit Animal(name)
    override _.Sound() = "meow"

type Fish(name) =
    inherit Animal(name)

let animals: Animal list = [Dog("Rex"); Cat("Tom"); Fish("Nemo")]

for a in animals do
    printfn "%s" (a.Speak())

The dog and the cat override Sound; the fish keeps the default.

member this.Speak() = $"{name} says {this.Sound()}"

Speak is written once, in the base class. It calls this.Sound(), and the call goes to the override of the actual object, even though Speak knows nothing about dogs or cats.

let animals: Animal list = [Dog("Rex"); Cat("Tom"); Fish("Nemo")]

The list has the type Animal list, so the dog, cat and fish are converted to their base class when they are put in it. The objects keep their own Sound.

λ dotnet fsi virtual.fsx
Rex says woof
Tom says meow
Nemo says ...

Calling the base implementation

An override often extends the base behaviour instead of replacing it. The base keyword calls the implementation of the base class.

base_call.fsx
type Employee(name: string, salary: decimal) =
    member _.Name = name
    member _.Salary = salary

    abstract Describe: unit -> string
    default _.Describe() = $"{name}, salary {salary}"

    abstract YearlyPay: unit -> decimal
    default _.YearlyPay() = salary * 12m

type Manager(name, salary, bonus: decimal) =
    inherit Employee(name, salary)

    override _.Describe() = base.Describe() + $", bonus {bonus}"
    override _.YearlyPay() = base.YearlyPay() + bonus

let staff: Employee list =
    [ Employee("Peter", 2400m)
      Manager("Lucia", 3100m, 5000m) ]

for e in staff do
    printfn "%s" (e.Describe())
    printfn "  yearly: %M" (e.YearlyPay())

A manager is an employee with a yearly bonus.

override _.YearlyPay() = base.YearlyPay() + bonus

base.YearlyPay() computes twelve monthly salaries as the base class does; the override only adds the bonus. The calculation is not repeated in the derived class.

λ dotnet fsi base_call.fsx
Peter, salary 2400
  yearly: 28800
Lucia, salary 3100, bonus 5000
  yearly: 42200

Abstract classes

An abstract member does not need a default. A class with such a member is an abstract class and must have the [<AbstractClass>] attribute. It describes what its derived classes have in common; only the derived classes create objects.

shapes.fsx
[<AbstractClass>]
type Shape(name: string) =
    member _.Name = name
    abstract Area: float
    abstract Perimeter: float

    member this.Report() =
        $"{name}: area {this.Area:F2}, perimeter {this.Perimeter:F2}"

type Circle(r: float) =
    inherit Shape("circle")
    override _.Area = System.Math.PI * r * r
    override _.Perimeter = 2.0 * System.Math.PI * r

type Rectangle(w: float, h: float) =
    inherit Shape("rectangle")
    override _.Area = w * h
    override _.Perimeter = 2.0 * (w + h)

let shapes: Shape list = [Circle(1.5); Rectangle(3.0, 4.0); Circle(0.5)]

for s in shapes do
    printfn "%s" (s.Report())

let total = shapes |> List.sumBy (fun s -> s.Area)
printfn "total area: %.2f" total

Shape declares an area and a perimeter, but it cannot compute them. Each derived class must override both members.

abstract Area: float

An abstract member without parameters is a property. The derived classes override it with override _.Area = ....

let total = shapes |> List.sumBy (fun s -> s.Area)

Functions working on Shape values work for every derived class, including classes written later.

λ dotnet fsi shapes.fsx
circle: area 7.07, perimeter 9.42
rectangle: area 12.00, perimeter 14.00
circle: area 0.79, perimeter 3.14
total area: 19.85

Abstract classes cannot be created

The compiler rejects an attempt to create an object of an abstract class. It also rejects a derived class that leaves an abstract member without an implementation.

abstract_new.fsx
[<AbstractClass>]
type Shape(name: string) =
    member _.Name = name
    abstract Area: float

let s = Shape("blob")

The script tries to create a Shape directly.

let s = Shape("blob")

The script fails to compile with error FS0759. An abstract class is only a template for its derived classes.

λ dotnet fsi abstract_new.fsx


abstract_new.fsx(6,9): error FS0759: Instances of this type cannot be created since it has been marked abstract or not all methods have been given implementations. Consider using an object expression '{ new ... with ... }' instead.

Type tests in a hierarchy

A value of the base type may hold any derived object. The :? pattern tests for a derived class, and :?> converts a base value to a derived one. Both work as described in F# obj type, but here the base type is our own class.

type_tests.fsx
[<AbstractClass>]
type Vehicle(model: string) =
    member _.Model = model
    abstract Wheels: int

type Car(model, seats: int) =
    inherit Vehicle(model)
    override _.Wheels = 4
    member _.Seats = seats

type Truck(model, load: float) =
    inherit Vehicle(model)
    override _.Wheels = 6
    member _.Load = load

let fleet: Vehicle list = [Car("Skoda Octavia", 5); Truck("Tatra 815", 12.5); Car("Fiat 500", 4)]

for v in fleet do
    match v with
    | :? Car as c -> printfn "%s, %d seats" c.Model c.Seats
    | :? Truck as t -> printfn "%s, %.1f t load" t.Model t.Load
    | _ -> printfn "%s" v.Model

let first = fleet.Head
let car = first :?> Car
printfn "%s has %d wheels and %d seats" car.Model car.Wheels car.Seats

let asVehicle = car :> Vehicle
printfn "%s" asVehicle.Model

A fleet holds cars and trucks as Vehicle values.

| :? Car as c -> printfn "%s, %d seats" c.Model c.Seats

Inside the vehicle, Seats is not visible. The type test checks whether the object is a car and binds it as c, which has all the members of Car. The wildcard case is needed because the compiler does not know all derived classes of Vehicle.

let car = first :?> Car

The downcast succeeds because the first vehicle is a car; for a truck it would raise InvalidCastException. The :> operator goes the other way, from a derived class to its base, and always succeeds.

λ dotnet fsi type_tests.fsx
Skoda Octavia, 5 seats
Tatra 815, 12.5 t load
Fiat 500, 4 seats
Skoda Octavia has 4 wheels and 5 seats
Skoda Octavia

Overriding ToString

Every class inherits from System.Object, the obj type. Its virtual members can be overridden like those of our own classes. ToString gives the text that is printed for the object.

tostring.fsx
type Temperature(celsius: float) =
    member _.Celsius = celsius
    override _.ToString() = $"{celsius:F1} °C"

type Plain(celsius: float) =
    member _.Celsius = celsius

let t = Temperature(21.456)
let p = Plain(21.456)

printfn "%O" t
printfn "%O" p
printfn $"inside: {t}"
printfn "%s" (string t)

The two classes are the same except for the ToString override.

override _.ToString() = $"{celsius:F1} °C"

%O, string interpolation and the string function all call ToString. Without an override, the inherited version returns the type name, as for the Plain class.

λ dotnet fsi tostring.fsx
21.5 °C
FSI_0001+Plain
inside: 21.5 °C
21.5 °C

Overriding Equals

Objects of a class are equal only when they are the same object; see F# classes. Overriding Equals compares them by their data instead. GetHashCode must be overridden together with it, so that equal objects have equal hash codes.

equals.fsx
type Point(x: int, y: int) =
    member _.X = x
    member _.Y = y

    override _.Equals(other) =
        match other with
        | :? Point as p -> x = p.X && y = p.Y
        | _ -> false

    override _.GetHashCode() = hash (x, y)
    override _.ToString() = $"({x}, {y})"

let a = Point(1, 2)
let b = Point(1, 2)
let c = Point(2, 1)

printfn "a = b: %b" (a = b)
printfn "a = c: %b" (a = c)
printfn "same object: %b" (obj.ReferenceEquals(a, b))

let points = [a; c; b; Point(2, 1); Point(0, 0)]
printfn "%A" (List.distinct points)

Two points are equal when their coordinates are equal.

override _.Equals(other) =
    match other with
    | :? Point as p -> x = p.X && y = p.Y
    | _ -> false

Equals receives an obj, so it first tests whether the other value is a point at all. The = operator calls this method.

override _.GetHashCode() = hash (x, y)

The hash code is computed from the same fields as equality. List.distinct, sets and maps use hash codes or comparison to find equal values. Records and unions get both methods from the compiler, which is why they are a better choice for plain data.

λ dotnet fsi equals.fsx
a = b: true
a = c: false
same object: false
[(1, 2); (2, 1); (0, 0)]

Sealed classes

A class with the [<Sealed>] attribute cannot be used as a base class. Records and unions are always sealed, and so are many .NET classes, such as String.

sealed.fsx
[<Sealed>]
type Token(value: string) =
    member _.Value = value

type SpecialToken(value) =
    inherit Token(value)

SpecialToken tries to inherit from a sealed class.

type SpecialToken(value) =
    inherit Token(value)

The compiler reports error FS0945. Sealing a class keeps its behaviour fixed: no derived class can override anything.

λ dotnet fsi sealed.fsx


sealed.fsx(6,13): error FS0945: Cannot inherit a sealed type

Construction order

When a derived object is created, the base constructor runs first. Its let and do bindings are done before those of the derived class.

order.fsx
type Base(name: string) =
    do printfn "Base: start %s" name
    let created = System.DateOnly(2026, 12, 3)
    do printfn "Base: done"
    member _.Created = created

type Middle(name: string) =
    inherit Base(name)
    do printfn "Middle: %s" name

type Leaf(name: string, size: int) =
    inherit Middle(name)
    do printfn "Leaf: size %d" size

let leaf = Leaf("item", 3)
printfn "created %s" (leaf.Created.ToString "yyyy-MM-dd")

Three classes form a chain: Leaf derives from Middle, which derives from Base.

let leaf = Leaf("item", 3)

Creating a leaf runs the constructors from the top of the chain down. Each class can rely on its base being complete when its own code runs.

λ dotnet fsi order.fsx
Base: start item
Base: done
Middle: item
Leaf: size 3
created 2026-12-03

Bank accounts

The last example models two kinds of bank accounts. The base class keeps the balance and the history; the derived classes decide what happens at the end of each month.

accounts.fsx
[<AbstractClass>]
type Account(owner: string, opening: decimal) =
    let mutable balance = opening
    let mutable history = []

    member _.Owner = owner
    member _.Balance = balance
    member _.History = List.rev history

    member _.Post(text: string, amount: decimal) =
        balance <- balance + amount
        history <- $"{text,-10} {amount,9:N2} {balance,10:N2}" :: history

    abstract MonthEnd: unit -> unit

type Savings(owner, opening, rate: decimal) =
    inherit Account(owner, opening)
    override this.MonthEnd() =
        let interest = System.Math.Round(this.Balance * rate / 12m, 2)
        this.Post("interest", interest)

type Checking(owner, opening, fee: decimal, freeAbove: decimal) =
    inherit Account(owner, opening)
    override this.MonthEnd() =
        if this.Balance < freeAbove then this.Post("fee", -fee)

let accounts: Account list =
    [ Savings("Lucia", 5000m, 0.03m)
      Checking("Peter", 800m, 2.5m, 1000m)
      Checking("Anna", 1500m, 2.5m, 1000m) ]

accounts[1].Post("salary", 1850m)
accounts[1].Post("rent", -950m)
accounts[2].Post("shop", -620m)

for month in 1 .. 2 do
    for a in accounts do
        a.MonthEnd()

for a in accounts do
    printfn "%s (%s)" a.Owner (a.GetType().Name)
    for line in a.History do
        printfn "  %s" line

Savings accounts earn interest; checking accounts pay a fee when the balance is below a limit.

member _.Post(text: string, amount: decimal) =
    balance <- balance + amount
    history <- $"{text,-10} {amount,9:N2} {balance,10:N2}" :: history

All changes to the balance go through Post, which also records a line in the history. The derived classes cannot change the balance in any other way, because balance is a private field of Account.

override this.MonthEnd() =
    if this.Balance < freeAbove then this.Post("fee", -fee)

The checking account reads the balance and posts the fee through members inherited from Account. The loop over the months calls MonthEnd on each account without knowing its kind. Anna's balance drops below 1,000 after shopping, so she pays the fee.

λ dotnet fsi accounts.fsx
Lucia (Savings)
  interest       12.50   5,012.50
  interest       12.53   5,025.03
Peter (Checking)
  salary      1,850.00   2,650.00
  rent         -950.00   1,700.00
Anna (Checking)
  shop         -620.00     880.00
  fee            -2.50     877.50
  fee            -2.50     875.00

Source

F# language reference: Inheritance

F# language reference: Abstract classes

F# language reference: Methods

In this article we have derived classes with inherit, declared virtual members with abstract and default, replaced them with override, called the base implementation, written abstract classes, tested types in a hierarchy, overridden ToString and Equals, and sealed a class. Classes are introduced in F# classes, and F# interfaces shows another way to give different types a common set of members.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.