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 ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.