Classes and inheritance in F#

This example is similar to the Classes in Ruby example. It demonstrates a superclass for representing a car. Two subclasses are used for representing a hero car and a villain car, they inherit from the superclass.

The Car module

// Car.fs
namespace ClassesAndInheritance

module Car = 

    type Car(model:string, maxSpeed:string, fuel:string) =
        let mutable model = model
        let mutable maxSpeed = maxSpeed
        let mutable fuel = fuel

        // Declare properties
        member this.Model
            with get() = model
            and set(value) = model <- value

        member this.MaxSpeed
            with get() = maxSpeed
            and set(value) = maxSpeed <- value

        member this.Fuel
            with get() = fuel
            and set(value) = fuel <- value

        // Declare the drive method
        member this.drive() = printfn "Driving.."

        // Override the ToString method
        override this.ToString() =
            "Model: " + model + "\n" + "Maximum speed: " + maxSpeed +
            "\n" + "Fuel: " + fuel

    // Inheritance

    type VillainCar(model:string, maxSpeed:string, fuel:string) =
        inherit Car(model, maxSpeed, fuel)
        // Override the drive method
        member this.drive() = printfn "Boo!"

    type HeroCar(model:string, maxSpeed:string, fuel:string) =
        inherit Car(model, maxSpeed, fuel)
        // override the drive method
        member this.drive() = printfn "Woo!"

The main program

// Program.fs

namespace ClassesAndInheritance

open System
open Car

module Program = 

    // Declare the main function
    let main() =
        let carBatman = HeroCar("Batmobile","531 km/h","High octane")
        let carJoker = VillainCar("Jokermobile","100 km/h","Helium");

        // Display both cars
        Console.WriteLine("Batman drives: ")
        Console.WriteLine(carBatman.ToString() + "\n")
        Console.WriteLine("The Joker drives: ")
        Console.WriteLine(carJoker.ToString() + "\n")

        // Drive both cars
        carBatman.drive()
        carJoker.drive()

        // Used for pausing the console application
        Console.ReadLine() |> ignore

    // Execute the main function
    main()

Output:

Batman drives:
Model: Batmobile
Maximum speed: 531 km/h
Fuel: High octane

The Joker drives:
Model: Jokermobile
Maximum speed: 100 km/h
Fuel: Helium

Woo!
Boo!

You may download the VS 2010 project from here.

This entry was posted in F# and tagged , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?