Aggregation and composition both represents has-an-assiociation:


Aggregation


Example for an aggregation


An object of class Course "owns" Students. But a Student is not owned exclusively by one course. He is possibly a part of other courses. Subsequently a the lifetime of owned objects is independent of lifetime of their owners. (If a course is closed, the student still exists in other ones.)

1 Student student = new Student();
2 Course course1 = new Course();
3 Course course2 = new Course();
4 
5 course1.addStudent(student);    // only the reference of student is copied 
6 course2.addStudent(student);    // and transferred by paraneter


Composition


Example for a composition


A Object of class Department is owned exclusively by the Object of class Company. A department is a part of company, which is not able to exists alone.
Therefore the lifetime of the object which represents a part, depends on the lifetime of the object which represents the owner. (A department object will be removed from memory at the same time the company object is removed.


1 Company company = new Company();
2 company.addDepartment(new Department());    // The department object is created during the parameter tranfer
3                                             // and therefore exists only within the company object


or without parameter e.g. in this way:


 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 
 4 public class Company {
 5     // a list holds more than one department
 6     private Collection<Department> departments = new ArrayList<Department>();
 7 
 8     public void createDepartment() {
 9         Department department = new Department(); // Even so, the object department does not exist 
10         departments.add(department);              // outside of a company
11     }
12 }
Last modified: Sunday, 5 May 2019, 6:22 PM