When should you prefer composition over inheritance?
Assesses fundamental understanding of OOP Concepts conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Inheritance is an is-a relationship: Dog extends Animal because every dog is an animal. Composition is a has-a relationship: Car holds an Engine. Inheritance gives reuse plus polymorphism but couples the child tightly to the parent's implementation. A change in the base class can silently break subclasses, and a subclass inherits everything, needed or not.
Composition builds behaviour from parts, so you can swap, decorate or test those parts independently.
class Logger { void log(String m) { System.out.println(m); } }
class Service {
private final Logger logger = new Logger();
void run() { logger.log("start"); }
}
The guidance to prefer composition means use inheritance only when the subtype truly is a substitutable kind of the base and the base was designed for extension. Otherwise inject collaborators behind interfaces. This keeps hierarchies shallow, avoids fragile base classes and makes behaviour easy to vary at runtime.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.