What’s the difference between Association, Aggregation, and Composition in Java?
What’s the difference between Association, Aggregation, and Composition in Java?
🚀 Java Interview Questions – Episode 4
💡 What’s the difference between Association, Aggregation, and Composition in Java?
These are all types of object relationships in OOP —
but they differ in strength and lifespan dependency.
Let’s break it down:
🔹 Association → A general relationship between two classes.
Example: A Teacher works in a School.
Both can exist independently.
class School { String name; void employ(Teacher teacher) { System.out.println(teacher.name + " works at " + this.name); } }
🔹 Aggregation → A "has-a" relationship, but with loose coupling.
Example: A Department has Professors,
but professors can exist without the department.
🧩 Think of it as weak ownership.
class Department { List<Professor> professors; Department(List<Professor> profs) { this.professors = profs; } }
🔹 Composition → A strong "has-a" relationship with tight coupling.
Example: A House has Rooms.
If the house is destroyed, so are the rooms.
🔒 This is strong ownership, with lifecycle dependency.
class House { private List<Room> rooms = new ArrayList<>(); House() { rooms.add(new Room()); rooms.add(new Room()); } }
🧠 TL;DR:
Composition > Aggregation > Association (in terms of coupling and dependency)