The Plain Picture#
A car has an engine — it isn't a kind of engine. If you want a car with a better engine, you swap the engine. You don't redesign the whole car family tree.
The Real Names#
Composition = building a class by holding other objects as fields and delegating work to them: a "has-a" relationship.
"Favour composition over inheritance" — one of the most quoted design guidelines (from the Design Patterns book, 1994).
The problem it avoids: the fragile base class — changes to a parent class silently break subclasses that depend on its internals.
Under the Hood#
The inheritance trap. Suppose StudyBuddy needs quizzes that are timed, quizzes that are proctored, and quizzes that are both:
Quiz
┌────────┴─────────┐
TimedQuiz ProctoredQuiz
│
TimedProctoredQuiz ?? — must extend both. Java can't. And each new feature doubles the classes.With composition:
interface Timer {
boolean expired();
}
interface Proctor {
boolean suspicious(String studentId);
}
class Quiz {
private final List<Question> questions;
private final Timer timer; // HAS a timer (could be a "no-limit" timer)
private final Proctor proctor; // HAS a proctor (could be a "does nothing" proctor)
Quiz(List<Question> questions, Timer timer, Proctor proctor) {
this.questions = questions;
this.timer = timer;
this.proctor = proctor;
}
boolean canSubmit(String studentId) {
return !timer.expired() && !proctor.suspicious(studentId); // DELEGATE to the parts
}
}Any combination of features is just different parts passed in. Parts can even change at runtime. And each part is easy to test in isolation with a fake.
When inheritance is right#
Use inheritance when all of these hold:
it's a true is-a relationship that won't change (a
MultipleChoicereally is aQuestion);the subclass can be used anywhere the parent is expected without surprises (the Liskov Substitution Principle, SOLID Principles);
you control both classes, or the parent was designed to be extended.
Otherwise, compose.
Check yourself
4 questions"Is-a" vs "has-a" — which is inheritance, which is composition?
Show answerHide answer
Is-a = inheritance; has-a = composition.
Why does inheritance struggle with "timed + proctored" quizzes?
Show answerHide answer
Each combination needs its own subclass (and Java has single inheritance), so classes multiply; composition just combines parts.
What's the fragile base class problem?
Show answerHide answer
Changes inside a parent class unexpectedly break subclasses that depend on its behaviour or internals.
When is inheritance a good choice?
Show answerHide answer
For a stable, true is-a relationship where the subclass can fully substitute for the parent, and the parent was designed for extension.