Mark As Completed Discussion

Association, Aggregation, and Composition

In object-oriented design, classes can have different types of relationships with each other. Three common types of relationships are association, aggregation, and composition.

Association

Association represents a relationship between two classes where each class has an independent existence and there is no ownership between them. It can be a one-to-one, one-to-many, or many-to-many relationship.

For example, let's consider the relationship between a Person class and a Company class. Multiple persons can be associated with a company, and a person can be associated with multiple companies. In this case, the Person and Company classes are associated with each other.

To illustrate this association in Java, we can have a Person class with a name attribute and a Company class with a list of employees. The Company class can have methods to hire employees and print the names of the employees:

SNIPPET
1```java
2class Person {
3
4    private String name;
5
6    public Person(String name) {
7        this.name = name;
8    }
9
10    public String getName() {
11        return name;
12    }
13}
14
15class Company {
16
17    private String name;
18    private List<Person> employees;
19
20    public Company(String name) {
21        this.name = name;
22        this.employees = new ArrayList<>();
23    }
24
25    public void hireEmployee(Person person) {
26        employees.add(person);
27    }
28
29    public void printEmployees() {
30        for (Person employee : employees) {
31            System.out.println(employee.getName());
32        }
33    }
34}
35
36public class Main {
37    public static void main(String[] args) {
38        Person person1 = new Person("Alice");
39        Person person2 = new Person("Bob");
40        Person person3 = new Person("Charlie");
41
42        Company company = new Company("ABC Corp");
43        company.hireEmployee(person1);
44        company.hireEmployee(person2);
45        company.hireEmployee(person3);
46
47        company.printEmployees();
48    }
49}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment