Junior
What is the difference between composition and inheritance?
sobes.tech AI
Answer from AI
Composition and inheritance are two main mechanisms of code reuse in OOP, but they represent different types of relationships between classes:
- Inheritance (
is-arelationship): The "is-a" relationship. A subclass extends or specializes the behavior of a superclass. The child class inherits fields and methods from the parent class. - Composition (
has-arelationship): The "has-a" relationship. A class contains instances of other classes as its members. It delegates part of its behavior to these contained objects.
Main differences:
| Attribute | Inheritance | Composition |
|---|---|---|
| Relationship | is-a (is a) | has-a (has) |
| Flexibility | Less flexible (fixed hierarchy) | More flexible (components can be changed) |
| Coupling | Strong coupling between classes | Weak coupling between classes |
| Polymorphism | Achieved through overriding | Achieved through delegation |
| Changes | Changes in the parent class can break subclasses | Changes in the contained class have less impact on others |
| Complexity | Can lead to "fragile base class problem" | Simpler code organization |
Example of inheritance:
class Animal {
void eat() {
// ...
}
}
class Dog extends Animal { // Dog is-a Animal
void bark() {
// ...
}
}
Example of composition:
class Engine {
void start() {
// ...
}
}
class Car {
private Engine engine; // Car has-a Engine
public Car() {
this.engine = new Engine();
}
void startCar() {
engine.start(); // Delegation
}
}
Overall, composition is preferred over inheritance in many cases because it provides greater flexibility and reduces coupling between classes. Inheritance should be used when there is a clearly defined "is-a" relationship, and the subclass truly extends the functionality of the base class.