Member-only story
Composition and Aggregation in Java
In Java, composition and aggregation define relationships between classes, allowing us to model real-world scenarios by linking objects within a program. These relationships enable classes to work together without being hierarchically dependent on each other, unlike inheritance. Here, we’ll explain these relationships with examples and scenarios for clear understanding. You can visit the detailed tutorial here.
1. Composition in Java
Composition represents a strong relationship between two classes. If an object (child) is a part of another object (parent), and cannot exist independently, this relationship is known as composition. The lifecycle of the contained (child) object is bound to the lifecycle of the container (parent) object. In simpler terms, if the parent object is destroyed, the child object is also destroyed.
Example: Car
and Engine
Let’s consider a Car
class that has an Engine
. Here, a car cannot function without an engine, and if the car is destroyed, the engine is as well. This scenario makes Engine
a part of Car
, demonstrating a "has-a" relationship.