Member-only story
Associations
In object-oriented programming, classes can be related to each other through associations, such as aggregation and composition. In aggregation, the contained object can exist independently of its container class, whereas in composition, the contained object is instantiated within the constructor of the container class, meaning it can only exist as part of it and for as long as it exists. Let’s look at an example:
class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Course {
private String name;
private Student[] students;
private int count;
public Course(String name, int capacity) {
this.name = name;
this.students = new Student[capacity];
this.count = 0;
}
public void addStudent(Student student) {
if (count < students.length) {
students[count++] = student;
} else {
System.out.println("Course is full");
}
}
public void listStudents() {
for (int i = 0; i < count; i++) {
System.out.println(students[i].getName());
}
}
}In the previous example, instances of the Student class can be associated with the Course class as part of its attributes, specifically in the students array. However, they can also exist independently, regardless of any Course instance.











