Sobes.tech
Middle

Why is composition more often recommended compared to inheritance?

sobes.tech AI

Answer from AI

  1. Flexibility: Composition allows changing the behavior of an object at runtime by adding or removing components. Inheritance provides a static hierarchy.
  2. Loose coupling: Objects using composition are less tightly coupled. Changing one component does not require changing all inheritors, as in inheritance.
  3. Reusability: Components can be used in different classes, promoting code reuse.
  4. Prevention of "diamond inheritance" problems: In languages with multiple inheritance (not Java), there can be issues with method duplication or conflicts. Composition does not have such problems.
  5. Better testability: Objects with composition are easier to test by substituting or isolating components.
  6. Clarity: Composition more explicitly demonstrates the "has-a" relationship, unlike the "is-a" relationship in inheritance.
Characteristic Composition Inheritance
Relationship Has-a (имеет-а) Is-a (является-а)
Flexibility High (at runtime) Low (static hierarchy)
Coupling Weak Strong
Reusability Components in different classes Class hierarchies
Recommended for Behavior changes, aggregation, composite objects Specializations, extension of existing behavior

Example of composition:

// Component interface
interface Engine {
    void start();
}

// Component implementation
class GasolineEngine implements Engine {
    @Override
    public void start() {
        System.out.println("Starting gasoline engine");
    }
}

// Class using composition
class Car {
    private Engine engine; // Composition: Car has an Engine

    public Car(Engine engine) {
        this.engine = engine;
    }

    public void startCar() {
        engine.start(); // Delegating call to component
    }
}
Why is composition more often recommended compared to… - sobes.tech