What if a relationship is so strong that the "part" is meaningless and cannot even exist without the "whole"?
This is the world of Composition.
Composition is the strongest form of association in object-oriented design. It models a “has-a” relationship between a whole and its parts—but unlike aggregation, composition comes with ownership and lifecycle dependency.
When you use composition, you're saying:
Composition is a special type of association that signifies strong ownership between objects. The “whole” class is fully responsible for creating, managing, and destroying the “part” objects. In fact, the parts cannot exist without the whole.
If the part makes no sense without the whole, use composition.
Imagine a House and its Rooms:
This is a textbook example of composition. The rooms are tightly bound to the house—not just logically, but in lifecycle and ownership as well.
Let’s model above example using code.
Room
classHouse
classHouse
creates, manages, and owns its Room
objects.Room
objects do not exist independently outside the context of the House
.Room
instances.House
is deleted (e.g., garbage collected), the Room
s are destroyed too.This demonstrates a true composition relationship—where object ownership and lifecycle are tightly coupled.
In UML class diagrams, composition is represented by a filled diamond (◆) at the “whole” end of the relationship.
This means:
House
owns multiple Room
s.Room
s do not exist independently.House
dies, the Room
s die with it.Use composition when:
Composition is a preferred alternative to inheritance when building flexible systems.
“Favor composition over inheritance.” — GoF Design Principle
For example:
Vehicle
can compose an Engine
interface.PetrolEngine
, ElectricEngine
, or HybridEngine
at runtime.This leads to cleaner, testable, and decoupled code.