When should you use composition instead of inheritance in Java?
Use inheritance for a true is-a relationship and composition for has-a. Composition is usually safer because the classes stay loosely coupled and you can change the part at runtime, while inheritance ties the child tightly to the parent.
Explain it simply
A Car is not a kind of Engine; a Car has an Engine. If you made Car extend Engine just to reuse start(), then Car would also inherit everything else an Engine does, and swapping a petrol engine for an electric one would mean rewriting the class. Keeping the engine as a field lets you replace it freely.
Example
interface Engine { String start(); }
class Petrol implements Engine { public String start() { return "petrol on"; } }
class Electric implements Engine { public String start() { return "silent on"; } }
class Car {
private final Engine engine; // composition: has-a
Car(Engine engine) { this.engine = engine; }
String start() { return engine.start(); }
}
// new Car(new Electric()).start() returns: silent onWhat to say in the interview
"I use inheritance only when the child really is a specialised version of the parent and honours its contract. Otherwise I prefer composition: it avoids the fragile base class problem, where a parent change breaks children, it hides the part's internals, and it allows swapping behaviour at runtime through an interface. The common advice is: favour composition over inheritance."
Common mistakes
- Extending a class only to reuse a couple of methods, for example extending ArrayList to build a Stack.