19.4. Reuse Through CompositionΒΆ

Inheritance is not the only way to reuse code. Composition occurs when an object stores a reference to one or more objects in one of its instance variables. The object is thus able to reuse code in the objects it embeds within itself.

For example, our LabeledPoint example could have been implemented as follows:

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

The first thing to notice about this version of LabeledPoint is that it does not inherit from Point. Instead, its constructor instantiates a Point and stores a reference to it in its point instance variable so that it can be used by the other methods.

Next, notice how the distanceFromOrigin() method reuses the code in Point` by invoking it. We say that ``LabeledPoint’s distanceFromOrigin() delegates its implementation to Point’s implementation.

Finally, notice how the __str__() method also reuses the code in Point by calling str(self.point).

You have attempted 1 of 2 activities on this page