Middle
What are the advantages of composition compared to inheritance in object-oriented programming?
sobes.tech AI
Answer from AI
- Flexibility: Composition allows easy modification of an object's behavior at runtime by changing components, whereas inheritance rigidly defines behavior in a class hierarchy.
- Avoidance of the multiple inheritance problem: Java does not support multiple class inheritance, unlike composition, which allows an object to consist of multiple other objects.
- Better adherence to the Single Responsibility Principle (SRP): Composition encourages creating small, specialized objects that perform a specific function, while inheritance can lead to bulky classes.
- Reduced coupling: Changes in a base class through inheritance can affect all derived classes. In composition, changes in a component only affect the object that uses it.
- Simpler testing: Components in composition are easier to test in isolation since they are independent objects.
- Ability to change behavior at runtime: Components of an object can be changed during program execution, providing greater dynamism. Example:
// Composition example
interface CanFly {
void fly();
}
class SimpleFly implements CanFly {
@Override
public void fly() {
System.out.println("Simple flying");
}
}
class RocketFly implements CanFly {
@Override
public void fly() {
System.out.println("Rocket flying");
}
}
class Bird {
private CanFly flyingBehavior;
public Bird() {
this.flyingBehavior = new SimpleFly();
}
public void setFlyingBehavior(CanFly flyingBehavior) {
this.flyingBehavior = flyingBehavior;
}
public void performFly() {
flyingBehavior.fly();
}
}
// In another part of the code:
Bird sparrow = new Bird();
sparrow.performFly(); // Simple flying
sparrow.setFlyingBehavior(new RocketFly());
sparrow.performFly(); // Rocket flying
Comparison:
| Aspect | Inheritance | Composition |
|---|---|---|
| Coupling | High: changes in base affect derived | Low: changes in components are isolated |
| Flexibility | Low: behavior is rigidly set in hierarchy | High: behavior changes by changing components |
| Multiple implementation | Limited (for interfaces in Java) | Easily achieved through including multiple objects |
| Testing | Can be complex | Easier to test components in isolation |
| SRP principle | Harder to follow, can lead to monoliths | Easier to follow, encourages small classes |