Extending by Delegating

Extension through delegation occurs when a class has methods that forward calls to identical operations supplied by another object. This technique makes available the behavior of the forwarded-to class on the class you are extending, but this is usually not the best way to achieve extension. If you want to inherit the exact methods of an existing class, the most straightforward approach is to subclass it. However, this is not always possible. The class whose behavior you need may be declared final—as String is, for example—or your class may already be subclassing something else. In these cases, you can extend your class through delegation.

CHALLENGE 26.6Suppose that you want to make a class in an existing hierarchy observable, ...

Get Design Patterns Java™ Workbook 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.