Using the Subclass in Place of the Superclass
Explore how polymorphism in D allows subclass objects to be used wherever superclass objects are expected. Understand how method overriding works with classes like Clock and AlarmClock, and see how inheritance hierarchy enables specialized behavior while maintaining compatibility with general types.
We'll cover the following...
Polymorphism
Since the superclass is more general and the subclass is more specialized, objects of a subclass can be used in places where an object of the superclass type is required. This is called polymorphism.
The concepts of general and specialized types can be seen in statements like “this type is of that type”: “alarm clock is a clock”, “student is a person”, “cat is an animal”, etc. Accordingly, an alarm clock can be used where a clock is needed, a student can be used where a person is needed, and a cat can be used where an animal is needed.
When a subclass object is being used as a superclass object, it does not lose its own specialized type. This is similar to the examples in real life: Using an alarm clock simply as a clock does ...