What is the difference between the Adapter and a plain wrapper class?
The main difference between the Adapter and a wrapper class lies in their purpose and level of abstraction: all adapters are wrappers, but not every wrapper is an adapter.
1. Purpose
- Adapter solves the architectural task of interface compatibility: it lets an object with a "wrong" interface work where a different one is expected.
- Wrapper simply adds functionality around an existing object (for example, logging, validation, caching) without changing the interface.
Example:
- Adapter: turns
playMP3()intoplay(String file): "translates" the interface. - Wrapper: adds logging to
play(String file): "extends" the behavior.
2. Interface
- Adapter usually changes the interface: it implements one (target) interface and calls methods of another (adapted) one.
- Wrapper keeps the same interface, simply wrapping calls with extra logic.
Example (Adapter):
java
class MediaAdapter implements MediaPlayer {
private OldPlayer player = new OldPlayer();
public void play(String file) { player.startPlayback(file); }
}Example (Wrapper):
java
class LoggingMediaPlayer implements MediaPlayer {
private MediaPlayer wrapped;
public void play(String file) {
System.out.println("Start playing " + file);
wrapped.play(file);
}
}3. Context of Use
| Criterion | Adapter | Wrapper |
|---|---|---|
| Purpose | Interface compatibility | Behavior extension |
| Changes the interface | Yes | No |
| Example use case | Integrating old and new code | Adding logging, caching |
| Level | Architectural | Behavioral |
4. Conclusion
Adapter is an "interface translator" that ensures compatibility. Wrapper is a "behavior decorator" that adds new capabilities without changing the contract. In other words, Adapter is needed to connect the incompatible, while Wrapper is needed to reinforce what is already compatible.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.