Junior
What is the difference between composition and aggregation?
sobes.tech AI
Answer from AI
Composition and aggregation are "part-whole" relationships between objects.
-
Composition: A strict relationship where the part cannot exist without the whole. Removing the whole also removes the parts. The lifecycle of the dependent part is fully determined by the whole. Example: Rooms (parts) in a House (whole). Without the House, the rooms do not exist.
// Example of composition: class Room { private String name; public Room(String name) { this.name = name; } // ... Room methods } class House { private List<Room> rooms = new ArrayList<>(); // Parts are created and managed by the whole public House() { rooms.add(new Room("Living Room")); // Creating a part within the whole rooms.add(new Room("Bedroom")); } // ... House methods } -
Aggregation: A weaker relationship where the part can exist independently of the whole. Removing the whole does not necessarily lead to the removal of parts. Parts can be linked to multiple different whole objects. Example: Car (whole) and Wheels (parts). Wheels can exist separately from a specific car and be used on another.
// Example of aggregation: class Wheel { private int size; public Wheel(int size) { this.size = size; } // ... Wheel methods } class Car { private List<Wheel> wheels = new ArrayList<>(); // Whole contains references to parts public Car(List<Wheel> wheels) { this.wheels = wheels; // Receiving parts from outside } // ... Car methods } // Example of creation and usage: List<Wheel> myWheels = new ArrayList<>(); myWheels.add(new Wheel(16)); myWheels.add(new Wheel(16)); // ... Car myCar = new Car(myWheels); // Aggregation: wheels can exist before and after the car
Main differences in the table:
| Criterion | Composition | Aggregation |
|---|---|---|
| Dependency | Strict: Part depends on the whole | Weak: Part can exist independently |
| Lifecycle | Part is managed by the whole | Part is not necessarily managed by the whole |
| Deletion of whole | Leads to deletion of parts | Does not necessarily lead to deletion of parts |
| Multiple links | Part belongs to only one whole | Part can be linked to multiple wholes |
| UML Diagram | Filled diamond on the whole side | Empty diamond on the whole side |