CHAPTER 5 UNDERSTANDING ENCAPSULATION
Car viper = new Car();
viper.TurnOnRadio(false);
}
The Role of Polymorphism
The final pillar of OOP is polymorphism. This trait captures a language’s ability to treat related objects in
a similar manner. Specifically, this tenant of an object-oriented language allows a base class to define a
set of members (formally termed the polymorphic interface) that are available to all descendents. A
class’s polymorphic interface is constructed using any number of virtual or abstract members (see
Chapter 6 for full details).
In a nutshell, a virtual member is a member in a base class that defines a default implementation
that may be changed (or more formally speaking, overridden) by a derived class. In contrast, an abstract
method is a member in a base class that does not provide a default implementation, but does provide a
signature. When a class derives from a base class defining an abstract method, it must be overridden by a
derived type. In either case, when derived types override the members defined by a base class, they are
essentially redefining how they respond to the same request.
To preview polymorphism, let’s provide some details behind the shapes hierarchy shown in
Figure 5-5. Assume that the Shape class has defined a virtual method named Draw() that takes no
parameters. Given the fact that every shape needs to render itself in a unique manner, subclasses such as
Hexagon and Circle are free to override this method to their own liking (see Figure 5-5).
Figure 5-5. Classical polymorphism
After a polymorphic interface has been designed, you can begin to make various assumptions in
your code. For example, given that Hexagon and Circle derive from a common parent (Shape), an array of
Shape types could contain anything deriving from this base class. Furthermore, given that Shape defines a
187