Member-only story

Composition and Aggregation in Java

Afzal Badshah, PhD
4 min readNov 12, 2024

--

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.

Composition in Java

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.

Code Example:

--

--

Afzal Badshah, PhD
Afzal Badshah, PhD

Written by Afzal Badshah, PhD

Dr Afzal Badshah focuses on academic skills, pedagogy (teaching skills) and life skills.

No responses yet