Inheritance
The Ant
class discussed in the first section of this chapter provided an example of how to define a class and then define the methods associated with the class. We will now extend the class by creating new classes that inherit from the base class. The original Ant
class is shown in the preceding figure, and now, we will propose four classes that inherit from the base class. Two new classes that inherit from Ant
are the Male
and Female
classes. The Worker
class inherits from the Female
class, while the Soldier
class inherits from the Worker
class. The relationships are shown in the following figure. The code for all of the new classes is included in our example codes available at our website, but we will only focus on two of the new classes in the text to keep our discussion more focused.
When a new class is created, it can inherit from an existing class by setting the contains
parameter. This can be set to...