| < Day Day Up > |
InheritanceAs mentioned earlier in this chapter, one of the most powerful attributes of OO programming is code reuse. Procedural programming provides code reuse to a certain degree ”you can write a procedure and then use it as many times as you want. However, OO programming goes an important step further, allowing you to define relationships between classes that facilitate not only code reuse, but also better overall design, by organizing classes and factoring in commonalties of various classes. Inheritance is a primary means of providing this functionality.
Inheritance allows a class to inherit the attributes and
One of the major design issues in OO programming is to factor out
Figure 1.14. Mammal hierarchy.
The Dog and Cat classes both inherit from Mammal . This means that a Dog class actually has the following attributes: eyeColor // inherited from Mammal barkFrequency // defined only for Dogs In the same vein, Dog object has the following methods: getEyeColor // inherited from Mammal bark // defined only for Dogs
When the
Dog
or the
Cat
object is
Superclasses and Subclasses
The superclass, or parent class, contains all the attributes and behaviors that are common to classes that inherit from it. For example, in the case of the
Mammal
class, all mammals have similar attributes such as
eyeColor
and
hairColor
, as well as behaviors such as
generateInternalHeat
and
growHair
. All mammals have these attributes and behaviors, so it is not necessary to duplicate them down the inheritance tree for each type of mammal. Thus, the
Dog
and
Cat
classes inherit all those common attributes and behaviors from the
Mammal
class. The
Mammal
class is
Inheritance provides a rich set of design advantages. When you're designing a
Cat
class, the
Mammal
class provides much of the functionality needed. By inheriting from the
Mammal
object,
Cat
already has all the attributes and behaviors that make it a true mammal. To make it more
Abstraction
An inheritance tree can grow quite large. When the
Mammal
and
Cat
classes are complete, other mammals, such as dogs (or lions,
Figure 1.15. Mammal UML diagram.
Note that the classes GermanShepherd and Poodle both inherit from Dog ”each contains only a single method. However, because they inherit from Dog , they also inherit from Mammal . Thus, the GermanShepherd and Poodle classes contain all the attributes and methods included in Dog and Mammal , as well as their own (see Figure 1.16). Figure 1.16. Mammal hierarchy.
Is-a RelationshipsConsider a Shape example where Circle , Square , and Star all inherit directly from Shape . This relationship is often referred to as an is-a relationship because a circle is a shape and Square is a shape. When a subclass inherits from a superclass, it can do anything that the superclass can do. Thus, Circle , Square , and Star are all extensions of Shape .
In Figure 1.17, the
Figure 1.17. The shape hierarchy.
|
| < Day Day Up > |