Java Reference
In-Depth Information
hierarchy that includes the inheritance relationship between the Mammal and
Horse classes.
There is no limit to the number of children a class can have or to the number
of levels to which a class hierarchy can extend. Two children of the same parent
are called siblings. Although siblings share the characteristics passed on by their
common parent, they are not related by inheritance, because one is not used to
derive the other.
In class hierarchies, common features should be kept as high in the hierarchy
as reasonably possible. That way, the only characteristics explicitly established
in a child class are those that make the class distinct from its parent and from its
siblings. This approach maximizes the potential to reuse classes. It also facilitates
maintenance activities, because when changes are made to the parent, they are
automatically reflected in the descendents. Always remember to maintain the is-a
relationship when building class hierarchies.
The inheritance mechanism is transitive. That is, a parent passes
along a trait to a child class, and that child class passes it along to
its children, and so on. An inherited feature might have originated
in the immediate parent or possibly several levels higher in a more
distant ancestor class.
There is no single best hierarchy organization for all situations. The deci-
sions you make when you are designing a class hierarchy restrict and guide
more detailed design decisions and implementation options, so you must make
them carefully.
Earlier in this chapter we discussed a class hierarchy that organized animals
by their major biological classifications, such as Mammal , Bird , and Reptile .
However, in a different situation, the same animals might logically be organized
in a different way. For example, as shown in Figure 9.4, the class hierarchy might
be organized around a function of the animals, such as their ability to fly. In this
case, a Parrot class and a Bat class would be siblings derived from a general
FlyingAnimal class. This class hierarchy is as valid and reasonable as the original
one. The needs of the programs that use the classes will determine which is best
for the particular situation.
KEY CONCEPT
Common features should be located
as high in a class hierarchy as is rea-
sonably possible.
FlyingAnimal
Parrot
Bat
Mosquito
FIGURE 9.4 An alternative hierarchy for organizing animals
 
Search WWH ::




Custom Search