See Introduction to classes: 18. Inheritance exercise.
The concept presented here is known as polymorphism. This refers to the practice of handling particular aspects or processing of objects differently based on their type. We can achieve this by overriding methods within derived classes. The point of defining a new class that inherits from a parent class is that the new class will have much in common with the parent class. For the commonalities, we provide and utilize inherited methods and class variables.
We have various choices concerning how to handle the differences between a child class and its parent class. One choice could be to define entirely new methods, with new names, to handle the differences, leaving the original methods intact. However, we only want to do this in cases where the original version of a particular method is still relevant to the derived class, and where we anticipate using the original method on a regular basis for instances of the derived class.
One major convenience associated with polymorphism, wherein we override a method, is that we can write code that anticipates the creation of derived classes, and that is ready to handle them. For example, if we have a program that draws shapes, we can define a parent
Shape class, and define a
draw method within it. We then derive lots of child classes for different shapes that all inherit from the
Shape class directly or indirectly. For each descendant class, we can create a
draw method that overrides the original. This overriding, as opposed to defining a drawing method with a different name, provides us with the convenience of always being able to rely on calling the
draw method to draw any shape, regardless of how many different classes we have derived from
Shape, and no matter how many new classes we may define in the future that derive from
Shape. It is something akin using an existing standard plug design when we invent a new appliance, so that we can rely on a standard outlet to power it that was designed long before the appliance was invented, or even anticipated. The plug, like the name of the
draw method for
Shape descendants, is the same for all appliances. We rely on each type of appliance to perform its own special magic when we power it on; we rely on each type of
Shape descendant to know how to display its glory when we call its