Java Reference
In-Depth Information
Chapter 17
Object Composition
An Alternative to Inheritance
Class inheritance is a powerful mechanism for reusing code, minimizing
data redundancy, and improving the organization of an object-oriented sys-
tem. However, inheritance is not always suitable. You saw that inheritance
is applied when classes are in a relationship in which the subclass “is a kind
of”the superclass. But this is not always the case. Often we have class rela-
tionships in which the subclass is “a part of”the superclass. Attempting to
apply inheritance in whole/part class relationships is an artificial and un-
natural solution. Fortunately, there is a simple alternative to inheritance as
a way of reusing class functionality, called object composition . In inheri-
tance, the subclass extends the functionality of a superclass. In object com-
position a class reuses functionality simply by declaring and holding an
object of the class it wants to reuse. In object composition, reusability is ac-
complished in a simpler manner.
Inheritance Drawbacks
One of the problems with inheritance can be simply stated: inheritance
breaks encapsulation . In the PetStore program, developed in Chapter 16,
the subclasses Dog, Cat, and Bird use the constructor of the superclass Pet
as well as some of its public methods. The data for the objects of the class
Dog, Cat, and Bird is centralized in the superclass Pet and the processing
operations are effectively reused in the superclass methods getName(),
getLocation(), and getPrice(). But for this to happen, the subclasses must
have knowledge of the structure of the superclass. A Dog object, a client ob-
ject of the Pet class, needs to know that Pet remembers name, location, and
price; even perhaps the type of variables where this data is stored. Although
the dog object has no direct access to the private data members of the
Search WWH ::




Custom Search