intermediateAdapter Pattern

In Java, why is object composition typically used to build an adapter instead of inheriting from the class being adapted?

An adapter built with composition holds a reference to the incompatible class as a field and delegates to it inside its own methods, which works even when the class being wrapped is final, has no default constructor, or is supplied to the adapter at runtime rather than known in advance. Java also only allows single inheritance, so if an adapter needed to extend the adapted class, it could never also extend anything else, and it would still need to implement the target interface separately. Composition keeps the adapter flexible -- it can wrap any instance handed to it, including ones created elsewhere -- and keeps the adapted class's internals genuinely private, exposed only through whatever the adapter's own methods choose to forward.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to Can you over-apply the Interface Segregation Principle? What's the downside of splitting interfaces too finely?← Back to all Low-Level Design & Design Patterns questions