Video in progress

What is composition and how does it differ from inheritance?

Composition is when a class keeps another object in a field and hands part of its work to it ("has-a": a car has an engine). Inheritance is an "is-a" relationship: the child class remains a type of the parent class.

📖 Answer

// Inheritance: ElectricCar is a Car
class ElectricCar extends Car { ... }

// Composition: a Car has an Engine
class Car {
    private final Engine engine;
    Car(Engine engine) { this.engine = engine; }
    void start() { engine.ignite(); }
}

The main differences:

  • Strength of coupling. With inheritance, the child is tied to the parent's internal structure; if the parent changes, the child can break. With composition you depend only on the object's public API.
  • Flexibility. Inheritance is fixed at compile time. With composition you can swap the Engine for another through the constructor: PetrolEngine, ElectricEngine, or a mock engine in a test.
  • Multiplicity. There is one parent, but you can have as many components as you like.

Ask yourself a simple question to check: "Is X a Y, or does X have a Y?" "An order has products" is composition. "An order is a product" makes no sense, so inheritance is wrong too.