f-sharp
  1. f-sharp-inheritance

F# Inheritance Inheritance

Inheritance is a fundamental aspect of object-oriented programming. Inheritance allows you to create a new class (the derived class) from an existing class (the base class). In this page, we will discuss inheritance in F#.

Syntax

The syntax for inheritance in F# is similar to that of C#. To create a new class based on an existing class, use the inherit keyword followed by the base class:

type DerivedClass() =
    inherit BaseClass()
    // class members go here

Example

Here's an example of inheritance in F#.

type Animal(name:string) =
    member this.Name = name
    member this.Move() = printfn "%s is moving." this.Name

type Dog(name:string) =
    inherit Animal(name)
    member this.Bark() = printfn "%s is barking." this.Name

In this example, we define two classes: Animal and Dog. Dog is a derived class of Animal. Dog inherits from Animal using the inherit keyword. The Dog class has an additional method called Bark which is not present in the base class.

Output

When we create an instance of the derived class, we can call all the members of the base class as well as the derived class.

let dog = Dog("Fido")
dog.Name |> printfn "Name: %s"   // Output: Name: Fido
dog.Move()                       // Output: Fido is moving.
dog.Bark()                       // Output: Fido is barking.

Explanation

Inheritance in F# is designed to be simple and straightforward. When a class is derived from another class, it automatically inherits all the members of the base class, including any properties, methods, or fields. The derived class can then add additional members or override existing ones.

In the example above, the Dog class inherits the Name property and Move() method from the base Animal class, while also adding its own Bark() method.

Use

Inheritance is useful when you want to create a new class that is similar to an existing class but with some variations or added functionality.

Important Points

Here are some important points to keep in mind when working with inheritance in F#:

  • You can only inherit from one base class in F#.
  • Inheritance only works for reference types, not for value types.
  • The base class constructor is called automatically when creating an instance of the derived class.

Summary

In this page, we discussed inheritance in F#. We covered the syntax, example, output, explanation, use, and important points of inheritance. Inheritance allows you to create new classes based on existing classes, and it is a fundamental aspect of object-oriented programming. By using inheritance, you can build new classes more efficiently by reusing code from existing classes.

Published on: