Video in progress
What is the difference between aggregation and composition? How do they look in Java code?
Both are "has-a" relationships. In composition, the part can't live without its owner: it is created with it and disappears with it. In aggregation, the part is independent: others use it too, and it stays even if the owner is gone.
📖 Answer
An example: an Order and its OrderLines are composition. The order creates the lines itself, doesn't hand them out, and when the order is deleted they go too.
class Order {
private final List<OrderLine> lines = new ArrayList<>(); // composition
void addLine(String sku, int qty) { lines.add(new OrderLine(sku, qty)); }
}
class Team {
private final List<Employee> members; // aggregation
Team(List<Employee> members) { this.members = List.copyOf(members); }
}
If a Team is disbanded, the employees stay in the company: they were passed in from outside and may belong to other teams too.
The syntax is the same; the difference is in lifecycle and ownership. In code you can tell by this:
- composition: the part is created with
newinside the constructor and isn't exposed in mutable form through a getter; - aggregation: the part is passed in from outside (through the constructor or DI).
The same difference exists in JPA: cascade = ALL, orphanRemoval = true fits composition, but not aggregation, since deleting a Team must not delete its Employees.
Sign up to mark studied questions and save your progress.