Composition vs inheritance
Inheritance says a type is another type and reuses its implementation. Composition says a type has another object and delegates work to it. Prefer composition unless you truly have an "is a" relationship.
Detailed Explanation
Both techniques reuse code. They bind you in different ways. If Car extends Engine, every car is an engine: callers can pass a car to a method that expects an engine, and a change to Engine is a change to Car. If Car holds an Engine field, the car can swap engines, expose only drive(), and ignore methods that make sense only for engines.
Inheritance is a compile-time, one-shot relationship in Java. You get one superclass. You inherit fields and methods you may not want. Stack extends Vector in the original JDK is the cautionary tale: a stack then had insertElementAt, which breaks the stack contract. Composition would have kept a private list and offered push and pop only.
Composition is ordinary fields. You choose the type of the field (Engine, or the interface PowerUnit). You choose whether callers see it. You can decorate, replace, or mock it. The price is forwarding methods if you need a large surface. That boilerplate is visible and boring, which is better than an invisible inherited surface you did not mean to publish.
Use inheritance when the subtype is substitutable in the Liskov sense, when you need polymorphism on a stable abstract type, and when the parent exists to share a genuine template. Exception hierarchies and small sealed families are fine. Use composition when you want reuse of implementation, when the reused type is concrete and changing, or when you would otherwise extend a class to "get its methods".
A practical test: if you find yourself overriding a method to throw UnsupportedOperationException, or hiding parent methods, you inherited the wrong type. Wrap it. Another test: if the parent is in a library, your subclass is coupled to every future parent method. A field of that library type isolates you.
The cost of composition is an extra object and some forwarding. The cost of inheritance is a rigid graph that is expensive to undo. Default to fields. Reach for extends when you can finish the sentence "a Child is a Parent" without wincing, and when callers will store children in parent-typed variables on purpose.
Code Examples
import java.util.ArrayList;
import java.util.List;
// Composition: a stack is not a List, it has a List.
public class IntStack {
private final List<Integer> values = new ArrayList<>();
public void push(int n) {
values.add(n);
}
public int pop() {
return values.remove(values.size() - 1);
}
public int size() {
return values.size();
}
public static void main(String[] args) {
IntStack s = new IntStack();
s.push(1);
s.push(2);
System.out.println(s.pop()); // prints: 2
System.out.println(s.size()); // prints: 1
}
}interface Clock {
long millis();
}
class SystemClock implements Clock {
@Override
public long millis() {
return System.currentTimeMillis();
}
}
class Expiry {
private final Clock clock; // composed; tests pass a fake clock
private final long deadline;
Expiry(Clock clock, long deadline) {
this.clock = clock;
this.deadline = deadline;
}
boolean expired() {
return clock.millis() >= deadline;
}
public static void main(String[] args) {
Clock frozen = () -> 1000L;
System.out.println(new Expiry(frozen, 500L).expired()); // prints: true
}
}Common Gotchas
Extending a concrete collection publishes every method
`extends ArrayList` gives `removeRange`, `ensureCapacity`, and future methods. Wrap a `List` instead.
Inheritance couples you to protected internals
a parent refactor of a protected field breaks children that compiled against the old shape.
Delegation is composition with forwarding
one field and a set of methods that call through is still composition, not inheritance.
Forcing "is a" for reuse
if you only want one helper method, extract a function or a small collaborator. Do not extend the helper's class.