Senior
What is the difference between composition and inheritance? Which is preferable?
sobes.tech AI
Answer from AI
Inheritance is a mechanism where one class (subclass) extends another (superclass), inheriting its properties and methods. This allows creating class hierarchies and reusing code.
Composition is when one object contains another object and delegates part of its functionality to it. Instead of inheritance, it uses object inclusion as fields.
Difference:
- Inheritance establishes an "is-a" relationship, while composition is "has-a".
- Inheritance tightly couples the subclass with the superclass, whereas composition is more flexible and allows changing components at runtime.
Which is preferable? In modern software design, composition is often preferred because it promotes loose coupling and better modularity. Inheritance should be used when there is a clear hierarchy and polymorphism.
Example of composition in Java:
class Engine {
void start() { System.out.println("Engine started"); }
}
class Car {
private Engine engine = new Engine();
void start() { engine.start(); }
}
Here, Car "has" an Engine, rather than inheriting it.