What is the difference between association, aggregation and composition, and what does the choice mean for your code?
The three words all mean one class refers to another, and they differ in how strong that reference is. Association is the general term: a teacher is associated with a school, and either may exist alone. Aggregation is association where the parts can exist independently of the whole, so a department holds employees but does not own their lifetimes. Composition is the strong case, where the parts cannot exist without the whole and are created and destroyed with it.
public class Main {
public static void main(String[] args) {
Department eng = new Department("Engineering");
eng.add(new Employee("Ada"));
eng.add(new Employee("Grace"));
System.out.println(eng.size());
eng.printAll();
}
}
class Department {
private final String name;
private final java.util.List<Employee> members = new java.util.ArrayList<>();
Department(String name) { this.name = name; }
void add(Employee e) { members.add(e); }
int size() { return members.size(); }
void printAll() {
for (Employee e : members) {
System.out.println(name + ": " + e);
}
}
}
class Employee {
private final String name;
Employee(String name) { this.name = name; }
public String toString() { return name; }
}The example shows aggregation. The department holds a list of employees, but the employees are constructed outside and passed in, so they exist independently and could be in two departments, in a reporting structure, or on their own. The department provides the grouping and the operations over the group, but it does not control the lifetime of its parts.
That is the practical difference to emphasise in an interview. Aggregation is modelled with a collection and an add method, and the parts are created by the caller. Composition is modelled the same way in code, but the whole creates the parts internally and there is no API for adding one from outside, so the one-to-many relationship cannot be broken.
In a class diagram, aggregation is drawn as a hollow diamond and composition as a filled one, but the language enforces nothing here. The diamond is documentation of an intention, and the intention has to be kept by the design: if you claim composition, the part must not be reachable from anywhere except the whole.