Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

When should you use composition instead of inheritance in Java?

SHORT ANSWER

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

java
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 on

What 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.

#java#oop#design

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.