Sitemap
Chevi

Computing & cooking. Clear and rigorous information with a strong and unwavering ethical commitment. Writing in spanish at bitácora.es since 2017.

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.

Press enter or click to view image in full size
Photo: Sebastian Sørensen

--

--

José Vicente del Valle Fayos
José Vicente del Valle Fayos

Written by José Vicente del Valle Fayos

He could have become a hedgehog tamer or a cava cork collector, but instead, he had the bright idea to study computer science.

Chevi
Chevi

Published in Chevi

Computing & cooking. Clear and rigorous information with a strong and unwavering ethical commitment. Writing in spanish at bitácora.es since 2017.