What is the difference between association, aggregation and composition, and what does the choice mean for your code?
All three are a relationship between two objects. The difference is how tightly the two are bound to each other and who owns the relationship.
public class Main {
public static void main(String[] args) {
Department eng = new Department("Engineering");
eng.add(new Employee("Ada"));
System.out.println(eng.size());
}
}
And here are the three in code.
// Association. The department knows the employee, but the
// employee can exist on its own.
public class Department {
private final java.util.List<Employee> members = new java.util.ArrayList<>();
public void add(Employee employee) {
members.add(employee);
}
}
// Aggregation. The department holds the employee, but the
// employee does not know about the department.
public class Team {
private final java.util.List<Employee> members = new java.util.ArrayList<>();
public void add(Employee employee) {
members.add(employee);
}
}
// Composition. The employee is part of the department and
// cannot be used without it.
public class Company {
private final java.util.List<Department> departments = new java.util.ArrayList<>();
public Department createDepartment(String name) {
Department department = new Department(name, this);
departments.add(department);
return department;
}
}
So what does the choice mean for your code? Here is the table.
the kind who owns it the parts can live alone
------------------ ------------------- --------------------------
association neither, it is just yes
a link
aggregation the whole yes
composition the whole no
And the difference in the code is really about the constructor and the lifetime. In aggregation the parts are created outside and then handed in. In composition the parts are created inside, and the whole owns them.
// Aggregation. The employee is made outside and handed in.
Team team = new Team();
Employee ada = new Employee("Ada");
team.add(ada);
// Composition. The employee is made inside and is not
// handed out.
Department department = new Department("Engineering");
department.add(new Employee("Ada"));
And the third row is the real difference. In composition the part cannot be used on its own, because it needs the whole to exist. And that is what makes composition safe, because the whole is in charge of the lifetime of the part and it can clean it up.
So the rule to remember is this. Association is a link, aggregation is a whole that holds parts, and composition is a whole that makes the parts and owns them for good.
The next two questions in this topic are about the plain meaning and about deciding between them.