Skip to content

Composition

Composition is a specialized form of association that represents a strong “has-a” relationship where one class (the whole/composite) owns objects of another class (the part), and the parts cannot exist independently of the whole.


A House contains Rooms:

  • If the house is destroyed, the rooms are destroyed too
  • A room cannot exist independently without a house
  • Rooms are not shared across houses
  • The house owns the rooms

CharacteristicDescription
Relationship”Part-of” (strong ownership)
LifetimePart depends on whole (same lifecycle)
SharingParts cannot be shared
Destroy parentChild objects are destroyed too
UMLFilled diamond (◆)

class Engine {
constructor(type, horsepower) {
this.type = type;
this.horsepower = horsepower;
this.isRunning = false;
}
start() { this.isRunning = true; }
stop() { this.isRunning = false; }
}
class Wheel {
constructor(position) {
this.position = position;
this.pressure = 32;
}
}
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
// Composition: Car creates and owns these components
this.engine = new Engine("V6", 300);
this.wheels = [
new Wheel("Front-Left"),
new Wheel("Front-Right"),
new Wheel("Rear-Left"),
new Wheel("Rear-Right")
];
}
start() {
this.engine.start();
console.log(`${this.make} ${this.model} started`);
}
}

AspectCompositionAggregation
OwnershipStrong (parent owns child)Weak (parent contains child)
LifetimeSame lifecycleIndependent lifecycles
SharingNot sharedCan be shared
UMLFilled diamond (◆)Empty diamond (◊)
Child dies with parent?YesNo
ExampleHouse has RoomsDepartment has Teachers

Previous Topic: Aggregation → Next Topic: Dependency →