CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
Understanding the Polymorphic Interface
When a class has been defined as an abstract base class (via the abstract keyword), it may define any
number of abstract members. Abstract members can be used whenever you wish to define a member
that does not supply a default implementation, but must be accounted for by each derived class. By
doing so, you enforce a polymorphic interface on each descendent, leaving them to contend with the
task of providing the details behind your abstract methods.
Simply put, an abstract base class’s polymorphic interface simply refers to its set of virtual and
abstract methods. This is much more interesting than first meets the eye, as this trait of OOP allows you
to build easily extendable and flexible software applications. To illustrate, you will be implementing (and
slightly modifying) the hierarchy of shapes briefly examined in Chapter 5 during the overview of the
pillars of OOP. To begin, create a new C# Console Application project named Shapes.
In Figure 6-7, notice that the Hexagon and Circle types each extend the Shape base class. Like any
base class, Shape defines a number of members (a PetName property and Draw() method, in this case) that
are common to all descendents.
Figure 6-7. The shapes hierarchy
Much like the employee hierarchy, you should be able to tell that you don’t want to allow the object
user to create an instance of Shape directly, as it is too abstract of a concept. Again, to prevent the direct
creation of the Shape type, you could define it as an abstract class. As well, given that you wish the
derived types to respond uniquely to the Draw() method, let’s mark it as virtual and define a default
implementation:
235