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
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
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
Each specialization of
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 ...