Cover by Chris Smith

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required