OOP · OOP Relationships
Composition
Promotes code reusability.
Advantages
- Promotes code reusability.
- Reduces object dependency.
- Improves flexibility.
- Makes applications easier to maintain
Real-World Problem
Imagine you are designing a House Management System. A House consists of multiple Rooms. If the House is demolished, all its Rooms are also destroyed. A Room cannot exist without a House because it is an integral part of it. This relationship is called Composition. What is Composition?
Composition is a strong HAS-A relationship in which one object completely owns another object. The lifecycle of the contained object depends on the lifecycle of the container object. If the container object is destroyed, the contained object is also destroyed. It represents strong ownership.
Diagram Explanation This diagram illustrates Composition using a House and a Room.
- A House contains one or more Rooms.
- The House has complete ownership of its Rooms.
- When the House is destroyed, the Rooms are also destroyed.
- A Room cannot exist independently without a House.
- Since the lifecycle of the Room depends entirely on the House, this relationship is called Composition.
Key Point: Composition represents a HAS-A relationship with strong ownership, where the contained object's lifecycle depends on the container object.
Key Characteristics

- HAS-A relationship.
- Strong ownership.
- Dependent lifecycle.
- The contained object cannot exist independently.

A strong "part-of" relationship: the whole creates and owns its parts; they die with it.
class Engine {
void start() { System.out.println("Engine running"); }
}
class Car {
private final Engine engine; // Car OWNS its engine
Car() {
this.engine = new Engine(); // created and controlled internally
}
void drive() { engine.start(); }
}
// When the Car is gone, its Engine is gone too — no shared ownership.