Java Reference
In-Depth Information
superclass, it needs to know about this data. This knowledge of the sub-
class about the internals of the private members of the superclass breaks
encapsulation.
A second possible problem with inheritance is that the subclasses
sometimes loose control of their own data. In the case of the PetStore ex-
ample developed in Chapter 16, the name, location, and price of a dog,
cat, or bird object are stored in the superclass Pet. The subclasses must
rely entirely on the methods of the superclass for accessing and changing
this data. If the class Pet does not provide a method for changing a pet's
name, then code would be unable to assign a new name to objects of Dog,
Cat, and Bird. Since the pet name data is stored in the superclass, a
change-of-name method cannot be simply implemented in a subclass. In
summary, by using inheritance, the subclass loses some degree of control
over its own objects.
Reusing Class Functionality
Application designers and programmers of object-oriented systems some-
times become so entangled in the mechanisms of inheritance that they for-
get simple options. In Java, a class can reuse the public members of another
class simply by instantiating an object of the class to be reused. When a
class uses the methods of another one by means of an object we say that re-
usability is achieved through object composition.
Object composition is based on the following simple facts of the Java
language:
1. A class can access the public members of another class.
2. A class can instantiate an object of another class.
3. An object can be a member of a class.
In describing object composition we use the terms client and host
class . The client class is the one that reuses the functionality and the host
class is the one that contains the functionality to be reused.
The new mind set
The inheritance model requires that we think of a class as being a kind-of
another one. In object composition the relationship between classes is un-
important. All we need to know is that a host class is located within the
scope of the client class and that the host contains public members that the
client class wants to access.
Search WWH ::




Custom Search