Composition over Inheritance in Java: When to Use Each
Compare composition and inheritance in Java, with examples of concrete collaborators, interface-backed substitution, delegation, and safe payment retries.
Composition can use concrete collaborators or interfaces when implementations need to vary. This article compares those choices with inheritance and applies delegation to Decorator, Strategy, and payment retries.
Composition over Inheritance in Java: When to Use Each
Treat “has-a” over “is-a” as a rule of thumb, not a ban on inheritance. Composition fits when an object owns another object or delegates work to it. Add an interface or inject the collaborator when substitution or a clear boundary is useful.
Introduction
The “composition over inheritance” principle recommends “has-a” relationships over “is-a” relationships — objects that contain other objects to obtain behavior, rather than classes that inherit behavior from parent classes. This is not a dismissal of inheritance; it is a response to the specific failure modes that inheritance creates when misused. The fragile base class problem is the core issue: subclasses that depend on parent implementation details break when the parent changes, even when the change seems unrelated to the subclass’s overrides. A concrete Stack extending ArrayList breaks because ArrayList exposes methods (like random access by index) that make no sense for a stack’s LIFO semantics.
Composition solves these problems through delegation: an object holds another object and calls it to do part of its work. The collaborator can be a concrete class. Use an interface when the caller needs to choose among implementations or when that contract makes a test boundary useful. Passing a collaborator into a constructor is dependency injection, but it is an option rather than a requirement for every composed object. Decorator and Strategy commonly use interfaces when behavior needs to be wrapped or replaced.
The examples compare cases where composition helps with cases where a stable subtype fits better. They also cover delegation, Decorator, and Strategy, plus failure modes such as a stack that exposes list operations callers can misuse.
When to Use
Use composition when:
- A “has-a” relationship better describes the model — a
Carhas anEngine, not is anEngine - You need behavior from multiple sources — Java single inheritance won’t allow extending multiple classes
- You want runtime flexibility — swap implementations without changing the class
- You need a replaceable collaborator — an interface can define the behavior callers may substitute
- You need to hide implementation details — wrap and delegate, don’t expose
One example, two choices
A car has an engine either way. If the engine type is fixed, composing with a concrete class keeps the code small. If a caller needs to select an engine, type that collaborator to an interface and pass it in. The second version adds a seam for substitution, along with another type and a little wiring.
public class CarCompositionExample {
interface Engine {
void start();
}
static final class GasEngine implements Engine {
public void start() {
System.out.println("Gas engine starting");
}
}
static final class ElectricEngine implements Engine {
public void start() {
System.out.println("Electric engine starting");
}
}
// Plain composition: this car uses one concrete engine type.
static final class FixedEngineCar {
private final GasEngine engine = new GasEngine();
void drive() {
engine.start();
System.out.println("Car driving");
}
}
// Interface-backed composition: the caller chooses the implementation.
static final class ReplaceableEngineCar {
private final Engine engine;
ReplaceableEngineCar(Engine engine) {
this.engine = engine;
}
void drive() {
engine.start();
System.out.println("Car driving");
}
}
public static void main(String[] args) {
new FixedEngineCar().drive();
new ReplaceableEngineCar(new ElectricEngine()).drive();
}
}
Save this as CarCompositionExample.java, then run javac CarCompositionExample.java && java CarCompositionExample:
Gas engine starting
Car driving
Electric engine starting
Car driving
| Choice | Use it when | Cost |
|---|---|---|
| Concrete collaborator | The implementation is fixed and there is no need to substitute it | Changing the type means editing the containing class |
| Interface and constructor injection | Tests or callers need different implementations behind one contract | Adds an interface and makes object wiring the caller’s job |
Both designs use composition. The interface pays off when substitution is a real requirement; it is extra indirection when the collaborator is fixed and simple.
When Not to Use
Don’t use composition when:
- True “is-a” relationship exists —
Dogis anAnimal, inheritance is appropriate - You need to override parent behavior — inheritance lets you override methods
- Shared immutable state — inheritance with
finalfields may be cleaner - Simple use cases — if inheritance is simpler and clear, use it (but be cautious)
// Valid inheritance: Dog truly is an Animal
public class Animal {
protected String name;
public void eat() { }
}
public class Dog extends Animal { // Dog IS an Animal
private String breed;
public void bark() { }
}
Dog dog = new Dog();
dog.eat(); // Inherited from Animal — appropriate here
Inheritance — Mermaid Diagram
flowchart TD
A1[Animal] --> B1[Dog]
A1 --> C1[Cat]
B1 --> D1[Terrier]
Composition — Mermaid Diagram
flowchart TD
A2[Order] --> B2[Payment]
A2 --> C2[Inventory]
A2 --> D2[Shipping]
Failure Scenarios
1. Force-Fitting Inheritance
// WRONG: Stack is not an ArrayList
public class Stack extends ArrayList {
public void push(Object item) { add(item); }
public Object pop() { return remove(size() - 1); }
}
// Problems:
// - ArrayList has methods like get(index), remove(index) that Stack shouldn't have
// - Invariants differ: ArrayList allows any index access, Stack only LIFO
// - Exposes 20+ methods that make no sense for a Stack
// CORRECT: Composition
public class Stack {
private final List<Object> items = new ArrayList<>();
public void push(Object item) { items.add(item); }
public Object pop() {
if (items.isEmpty()) throw new IllegalStateException("Empty");
return items.remove(items.size() - 1);
}
}
2. Fragile Base Class Problem
public class Base {
public List<String> getItems() {
return items; // Returns mutable list — subclasses can break this!
}
protected List<String> items = new ArrayList<>();
}
public class Derived extends Base {
public void addItem(String item) {
items.add(item); // Modifies the list from Base
}
}
// If Base changes to return defensive copy, Derived may break
// If Base changes internals, Derived behavior may change unexpectedly
3. Tight Coupling via Inheritance
Inheritance locks a class into its parent’s behavior contract. When you extend HashMap, you inherit every public and protected method — containsValue, remove(Object key, Object value), clear, putAll — whether your subclass needs them or not. The compiler enforces nothing about semantic compatibility. A HashMapExtended that only intended to add logging to put still carries all the other methods that clients can call, potentially violating invariants your subclass depends on.
More critically, HashMap’s internal representation — its bucket array, collision handling, and hash distribution — isn’t guaranteed by the Map interface. In Java 8 and later, a collision-heavy bucket can be treeified into a red-black tree after certain thresholds are reached; most buckets remain lists. Code that relies on bucket structure or iteration order is still fragile across implementations and versions. There’s no way to swap HashMap for LinkedHashMap or TreeMap in a subclass without rewriting the class. Here, a wrapper typed to Map is useful when the implementation or ordering needs to vary; an internal map with a fixed role can simply use a concrete type.
// Inheritance creates tight coupling — any HashMap change propagates down
public class HashMapExtended extends HashMap {
// Problem: exposes all 30+ HashMap methods to callers
// Problem: relies on HashMap bucket structure not in any contract
// Problem: cannot switch to LinkedHashMap without rewriting the class
// Problem: internal refactoring in HashMap can silently break this class
}
Composition with the Map interface addresses that specific coupling. A wrapper can accept any Map implementation and delegate to it, exposing only the methods it needs. The backing map can then be swapped for tests (HashMap), insertion order (LinkedHashMap), or sorted keys (TreeMap) without changing the wrapper.
Trade-off Table
| Aspect | Inheritance | Composition |
|---|---|---|
| Coupling | Subclass depends on parent contract and often its internals | Concrete collaborators are direct; an interface can reduce coupling when substitution matters |
| Flexibility | Fixed at compile-time | Can swap implementations at runtime |
| Reuse | Inherited code runs in subclass context | Delegated code runs in wrapper context |
| Testing | Tests may depend on parent behavior | A replaceable collaborator can use a test double; a fixed collaborator needs no mock seam |
| Hierarchy depth | Deep hierarchies problematic | Shallow, flexible structures |
Code Snippets
Delegation / Composition with Interface
public interface Logger {
void log(String message);
}
public class ConsoleLogger implements Logger {
@Override
public void log(String message) {
System.out.println("[CONSOLE] " + message);
}
}
public class FileLogger implements Logger {
@Override
public void log(String message) {
// Write to file
System.out.println("[FILE] " + message);
}
}
public class Service {
private final Logger logger; // Composed, not inherited
public Service(Logger logger) {
this.logger = logger;
}
public void doWork() {
logger.log("Work started");
// Do work
logger.log("Work completed");
}
}
Decorator Pattern (Runtime Behavior Addition)
public interface DataSource {
void write(String data);
String read();
}
public class FileDataSource implements DataSource {
private final String filename;
public FileDataSource(String filename) {
this.filename = filename;
}
@Override
public void write(String data) {
Files.writeString(Path.of(filename), data);
}
@Override
public String read() {
return Files.readString(Path.of(filename));
}
}
// Decorator adds encryption without changing FileDataSource
public class EncryptionDataSource implements DataSource {
private final DataSource wrapped;
public EncryptionDataSource(DataSource wrapped) {
this.wrapped = wrapped;
}
@Override
public void write(String data) {
wrapped.write(encrypt(data));
}
@Override
public String read() {
return decrypt(wrapped.read());
}
private String encrypt(String data) { /* ... */ return data; }
private String decrypt(String data) { /* ... */ return data; }
}
// Usage — behaviors composed at runtime
DataSource source = new EncryptionDataSource(
new CompressionDataSource(
new FileDataSource("data.txt")
)
);
Strategy Pattern
public interface DiscountStrategy {
double apply(double price);
}
public class NoDiscount implements DiscountStrategy {
@Override
public double apply(double price) { return price; }
}
public class PercentageDiscount implements DiscountStrategy {
private final double percent;
public PercentageDiscount(double percent) {
this.percent = percent;
}
@Override
public double apply(double price) {
return price * (1 - percent / 100);
}
}
public class FixedDiscount implements DiscountStrategy {
private final double amount;
public FixedDiscount(double amount) {
this.amount = amount;
}
@Override
public double apply(double price) {
return Math.max(0, price - amount);
}
}
public class Product {
private final String name;
private final double price;
private DiscountStrategy discountStrategy;
public Product(String name, double price, DiscountStrategy discountStrategy) {
this.name = name;
this.price = price;
this.discountStrategy = discountStrategy;
}
public double getFinalPrice() {
return discountStrategy.apply(price);
}
public void setDiscountStrategy(DiscountStrategy strategy) {
this.discountStrategy = strategy; // Can change at runtime
}
}
Observability Checklist
- “Has-a” better describes relationship than “is-a”
- Use an interface or abstract type when a collaborator needs to be replaceable
- Pass a collaborator into the constructor when the caller should control its choice
- Add a test double only when substituting the collaborator helps test the class
- Delegation explicit — methods forward to composed objects
Security Notes
- Narrow collaborator contracts — keep each dependency limited to the operations it needs; still validate and authorize its behavior
- Sealed classes — if inheritance is needed, control which classes can extend (Java 17+)
- Don’t expose internal collaborators — keep composed objects private
- Validate required collaborators — check constructor-supplied dependencies when null is not a valid value
public class SecureService {
private final Logger logger;
private final Validator validator;
// Constructor-supplied dependencies are explicit and easy to replace
public SecureService(Logger logger, Validator validator) {
if (logger == null) throw new IllegalArgumentException("Logger required");
if (validator == null) throw new IllegalArgumentException("Validator required");
this.logger = logger;
this.validator = validator;
}
}
Pitfalls
- Over-composition — turning everything into small interfaces when a class would suffice
- Missing delegation — forgetting to forward calls to composed objects
- Exposing composed objects — returning internal objects defeats encapsulation
- Wrapper overhead — each wrapper adds a method call (usually negligible)
- Composition without clear ownership — unclear who owns lifecycle of composed objects
// Bad: composition without delegation
public class Wrapper {
private final Inner inner;
public Wrapper(Inner inner) {
this.inner = inner;
}
// WRONG: inner never used — composition without delegation!
public void doSomething() {
// Just does its own thing, ignores inner
}
}
// Good: composition with delegation
public class Wrapper {
private final Inner inner;
public Wrapper(Inner inner) {
this.inner = inner;
}
public void doSomething() {
inner.doSomething(); // Delegates to composed object
}
}
Production Failure Scenarios
Composition keeps a subclass from inheriting APIs it should not expose, but composed behavior can still fail when wrappers are wired in the wrong order. A common example is retrying a payment operation after a timeout. The gateway may have charged the card even though the response was lost; retrying can charge it twice.
public final class RetryingPayment implements PaymentGateway {
private final PaymentGateway delegate;
public RetryingPayment(PaymentGateway delegate) {
this.delegate = delegate;
}
@Override
public Receipt charge(Payment payment) {
try {
return delegate.charge(payment);
} catch (TransientGatewayException timeout) {
// A timeout does not prove that the first charge failed.
return delegate.charge(payment);
}
}
}
In production, customers report duplicate charges while service logs show a timeout followed by a successful retry. Make the operation idempotent with a stable payment request key, and have the gateway return the original result for repeated keys. Keep retries in a decorator only when the operation’s contract makes retrying safe; alert on repeated requests and reconcile uncertain outcomes instead of assuming every timeout means failure.
Inheritance can produce a quieter version of the same problem: a subclass may preserve its parent’s method signatures while a parent change alters the order or side effects of those methods. Symptoms include overrides being skipped, duplicate hooks, or a subclass invariant breaking after a library upgrade. Keep inheritance shallow and based on documented extension points. If callers need one capability with multiple possible implementations, a small interface can define that boundary; use a concrete collaborator when the choice is fixed.
Security and Compliance Notes
An interface describes methods, not trust. A collaborator supplied from outside the class, whether through dependency injection or another form of wiring, can still be misconfigured or violate its contract. Put authorization at the use-case boundary, validate values before delegation, and avoid treating a wrapper as a substitute for access control. For regulated data, keep audit and retention requirements visible in the service boundary and verify that required decorators cannot be omitted from production wiring.
public final class AuthorizedPaymentService {
private final PaymentGateway gateway;
private final PaymentPolicy policy;
public AuthorizedPaymentService(PaymentGateway gateway, PaymentPolicy policy) {
this.gateway = Objects.requireNonNull(gateway);
this.policy = Objects.requireNonNull(policy);
}
public Receipt charge(User user, Payment payment) {
Objects.requireNonNull(user);
Objects.requireNonNull(payment);
policy.requireCanCharge(user, payment);
return gateway.charge(payment);
}
}
Do not log payment details or raw personal data from a decorator just because it sits around the gateway. Log a request identifier and the outcome needed for investigation, with sensitive values redacted. Review decorator order as part of security review: encryption must happen before data crosses an untrusted storage boundary, and logging or metrics wrappers must not capture secrets. Tests should exercise the assembled production chain as well as the individual collaborators.
Common Pitfalls and Anti-Patterns
Delegation is easy to make incomplete. A wrapper that forwards get to one object and put to another can appear correct in isolated tests, then return stale values under real use. Keep one clear delegate for each contract and forward every supported operation consistently. If the wrapper intentionally changes semantics, document that contract rather than presenting it as a drop-in replacement.
public final class CachedCatalog implements Catalog {
private final Catalog delegate;
private final Map<String, Item> cache = new HashMap<>();
public CachedCatalog(Catalog delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
@Override
public Item find(String id) {
return cache.computeIfAbsent(id, delegate::find);
}
@Override
public void save(Item item) {
delegate.save(item);
cache.put(item.id(), item); // Keep reads consistent after writes.
}
}
The cache example also needs an explicit concurrency and invalidation policy if multiple threads can update the catalog. Other warning signs are wrappers that expose their internal collaborators, chains whose order is undocumented, and strategies that keep mutable state shared across requests. Use constructor injection when the caller should provide a required collaborator; create a fixed internal detail directly when that keeps the design simpler. Prefer immutable strategy objects where possible, and test both wrappers and any wiring that affects behavior. Composition should make ownership and behavior clearer; if every call requires tracing through several opaque layers, simplify the chain.
Quick Recap
- Composition = “has-a” relationship; objects contain other objects to get behavior
- Inheritance = “is-a” relationship; subclass automatically gets parent behavior
- Favor composition when behavior might change, multiple sources of behavior needed, or coupling should be minimized
- Decorator pattern = runtime addition of behavior via composition
- Strategy pattern = runtime selection of behavior via composition
- Delegation = forward calls to composed objects, not inherit their implementation
Quick Recap Checklist
- Check whether the relationship is really “has-a” or a valid “is-a” subtype.
- Use a small interface when a collaborator needs a stable, replaceable contract.
- Pass changeable collaborators into the class when the caller should choose the implementation.
- Delegate deliberately, and keep internal collaborators private.
- Use Decorator to wrap behavior and Strategy to swap an algorithm.
- Keep inheritance when the subtype honors a stable parent contract.
Interview Questions
- Inheritance in Java — when “is-a” relationships are appropriate
- Interfaces in Java — contracts enabling composition
- Polymorphism in Java — polymorphic behavior with composed objects
- Effective Java: Item 18 — prefer composition over inheritance
- Effective Java: Item 19 — design and document for inheritance or else prohibit it
Conclusion
Composition uses “has-a” relationships: an object can hold another object and delegate work to it. The collaborator may be a concrete class. An interface reduces coupling when implementations need to vary or the contract gives tests a useful seam. Decorator and Strategy use that flexibility to wrap or select behavior.
Use composition when the model has a “has-a” relationship or when subclassing would expose operations the class should not have. Use an interface only when substitution matters. Inheritance still fits a true “is-a” relationship with a stable contract the subtype can honor.
This principle directly addresses the risks of inheritance by providing an alternative that avoids the tight coupling and fragile hierarchies that inheritance can create.
Summary
Composition lets a Java class delegate work to another object. Keep a concrete collaborator when its implementation is fixed; add an interface and pass it in when callers need to substitute behavior. Use inheritance when the subtype relationship is real and its contract holds.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.