Java Reference
In-Depth Information
return "("+x+", "+y+")";
}
This time, executing
System.out.println(p1);
results in more meaningful
output, such as
(10, 20)
.
Composition
Implementation inheritance and composition offer two different approaches to reusing
code. As you have learned, implementation inheritance is concerned with extending a
classwithanewclass,whichisbaseduponan“is-a”relationshipbetweenthem:a
Car
is a
Vehicle
, for example.
On the other hand,
composition
is concerned with composing classes out of other
classes,whichisbasedupona“has-a”relationshipbetweenthem.Forexample,a
Car
has an
Engine
,
Wheel
s, and a
SteeringWheel
.
Youhavealreadyseenexamplesofcompositioninthischapter.Forexample,
Listing
Car
class provides another example of composition.
Listing 2-28.
A
Car
class whose instances are composed of other objects
class Car extends Vehicle
{
private Engine engine;
private Wheel[] wheels;
private SteeringWheel steeringWheel;
}
Listing 2-28
demonstrates that composition and implementation inheritance are not
mutually exclusive. Although not shown,
Car
inherits various members from its
Ve-
hicle
superclass, in addition to providing its own
engine
,
wheels
, and
steer-
ingwheel
instance fields.
The Trouble with Implementation Inheritance
Implementation inheritance is potentially dangerous, especially when the developer
does not have complete control over the superclass, or when the superclass is not de-
signed and documented with extension in mind.