What is the difference between inheritance and composition?
Inheritance models an is a relationship, where a child class is a kind of the parent, and it reuses the parent by extending it. Composition models a has a relationship, where one class holds another class as a field and uses its behaviour. Modern advice is to favour composition because it is more flexible and creates looser coupling than deep inheritance.
The simple test: is a versus has a
Ask yourself whether the relationship is an is a or a has a. A Dog is an Animal, so inheritance fits. A Car has an Engine, so composition fits. Getting this test right is most of the answer.
Inheritance example
class Animal { void eat() {} }
class Dog extends Animal { } // Dog is an Animal
Composition example
class Engine { void start() {} }
class Car {
private Engine engine = new Engine(); // Car has an Engine
void start() { engine.start(); }
}
Why teams often prefer composition
- Flexibility: you can swap the inner object for another type at run time.
- Loose coupling: the outer class depends on behaviour, not on a rigid parent hierarchy.
- Avoids fragile base class problems where a parent change breaks many children.
The phrase interviewers love is favour composition over inheritance. Say inheritance for a clear is a relationship and composition for a has a relationship, then explain that composition keeps designs flexible. That single sentence signals real experience.
Common follow up questions
Related interview questions
Want the full OOP guide?
Read every OOP concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the OOP guide All OOP questions