Inheritance and composition are two object-oriented techniques used to achieve code reuse. Inheritance allows a class to acquire properties and behaviors from another class, while composition builds a class by combining objects of other classes. Composition is generally considered more flexible because it promotes loose coupling.
A Dog is an Animal.
A Car has an Engine.
// Inheritance Example
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
// Composition Example
class Engine {
void start() {
System.out.println("Engine Started");
}
}
class Car {
private Engine engine = new Engine();
void startCar() {
engine.start();
}
}A concise interview answer is
Inheritance is an 'is-a' relationship where a class extends another class and reuses its behavior. Composition is a 'has-a' relationship where a class contains objects of other classes. Composition is generally preferred because it provides better flexibility, loose coupling, and easier maintenance.
Last updated: 16 July 2026
Previous question: Why is multiple inheritance not supported in Java?