20.4. Reuse Through Association¶
Inheritance is not the only way to reuse code. Association occurs when an object stores a reference to one or more objects from a different class in one of its instance variables (attributes). The object is thus able to execute code on the objects it embeds within itself.
For example, our
LabeledPoint example could have been implemented as follows:
The first thing to notice is that
does not inherit from
Point in the code above. Instead, its constructor
Point and stores a reference to it in its
instance variable so that it can be used by the other methods.
Next, notice how the
distanceFromOrigin() method uses the code in
Point` by invoking it. We say that ``LabeledPoint’s
delegates its implementation to
Finally, notice how the
__str__() method also uses the code in
Point by calling