You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

Inheritance

So far I have covered classes, but not polymorphism, which is the magic that makes object-oriented programming so powerful. Consider the following two classes, a delicious BLTSandwich and the standard TurkeyAndSwissSandwich:

type BLTSandwich() =
    member this.Ingredients = ["Bacon"; "Lettuce"; "Tomato"]
    member this.Calories = 450
    override this.ToString() = "BLT"

type TurkeySwissSandwich() =
    member this.Ingredients = ["Turkey"; "Swiss"]
    member this.Calories = 330
    override this.ToString() = "Turkey and Swiss"

Even though both classes are nearly identical, they are different entities. So in order to write a function that accepts both an instance of BLTSandwich and an instance of TurkeySwissSandwich, you will need to resort to method overloading. Also, we would have to add a new overload method whenever we added a new sandwich type.

    member this.EatLunch(sandwich : BLTSandwich) = (*...*)

    member this.EatLunch(sandwich : TurkeySwissSandwich) = (*...*)

    // This will need to be added later...
    member this.EatLunch(sandwich : ClubSandwich) = (*...*)

The right way to think about this is that both of these tasty snacks are specializations of the same base type: Sandwich; and can customize the general properties and methods of a Sandwich. Each specialization of Sandwich will have a different calorie count and list of ingredients.

Moreover, you can continue to create a class hierarchy to specialize even further: Perhaps create a BLTWithPickelsSandwich type. This is exactly how inheritance ...

The best content for your career. Discover unlimited learning on demand for around $1/day.