15.2 Method Delegation: Putting It All Together
We use inheritance to extend a class’s behavior. On the other hand, we use delegation to
rely upon contained or aggregated objects to provide a class’s behavior.
We should choose inheritance if we intend to use an object in place of another object, and delegation
if we intend to simply use an object. Reserve inheritance for is-a or kind-of relationships; we
should prefer delegation over inheritance most of the time (see Effective Java [Blo08]).
However, it’s easy to program inheritance—it takes only one keyword,
extends. But it’s hard to program delegation, because we have to write all those methods that route the call to the contained objects. Groovy helps us do the right thing. By using ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access