Junior
What are the advantages of composition in object-oriented programming?
sobes.tech AI
Answer from AI
Composition offers the following advantages:
- Flexibility: Allows easy replacement or modification of parts of the object by changing or swapping the objects it contains, without altering the container class itself.
- Reusability: Enables the creation of complex objects by combining simpler, reusable objects.
- Loose coupling: Reduces dependencies between classes. Changing the internal representation of one component does not affect classes that use the container object, as long as the component interface remains unchanged.
- Testability: Simplifies testing, as components can be tested individually.
- Improved readability and maintainability: The code becomes more understandable because each part of the system has a clearly defined role.
Unlike inheritance, which creates an "is-a" relationship, composition creates a "has-a" relationship. This helps avoid problems with "fragile base class" issues and inheritance hierarchies that can become too complex and rigid.
Example:
Instead of creating multiple classes through inheritance:
// Not recommended
class Vehicle { /* ... */ }
class Car extends Vehicle { /* ... */ }
class Truck extends Vehicle { /* ... */ }
You can use composition to add functionality:
// Recommended
interface Engine { void start(); }
class GasEngine implements Engine { public void start() { /* ... */ } }
class ElectricEngine implements Engine { public void start() { /* ... */ } }
class Vehicle {
private Engine engine;
public Vehicle(Engine engine) {
this.engine = engine;
}
public void start() {
engine.start();
}
}
This allows easy creation of different types of vehicles with different engines without the need to create a new inheritance tree for each combination of features.