what is association in java with example
In Java, association represents a relationship between two or more classes where objects of one class are related to objects of another class. It defines how objects are related to each other and how they collaborate. There are different types of associations, such as one-to-one, one-to-many, and many-to-many.
Here’s an example to illustrate association in Java using a one-to-many association:
Let’s consider two classes: Department
and Employee
. A Department
can have multiple Employee
objects, but an Employee
can belong to only one Department
.
/*
* Author: Zameer Ali
* */
// Employee class
public class Employee {
private String name;
private int employeeId;
public Employee(String name, int employeeId) {
this.name = name;
this.employeeId = employeeId;
}
// Getters and setters for name and employeeId
// ...
}
// Department class
import java.util.List;
import java.util.ArrayList;
public class Department {
private String departmentName;
private List<Employee> employees;
public Department(String departmentName) {
this.departmentName = departmentName;
this.employees = new ArrayList<>();
}
public void addEmployee(Employee employee) {
employees.add(employee);
}
public List<Employee> getEmployees() {
return employees;
}
// Other methods related to the department
// ...
}
// Association example
public class AssociationExample {
public static void main(String[] args) {
// Creating employees
Employee employee1 = new Employee("John", 1);
Employee employee2 = new Employee("Alice", 2);
// Creating a department
Department department = new Department("Engineering");
// Associating employees with the department
department.addEmployee(employee1);
department.addEmployee(employee2);
// Retrieving employees from the department
List<Employee> employees = department.getEmployees();
// Displaying employees' information
for (Employee employee : employees) {
System.out.println("Employee ID: " + employee.employeeId + ", Name: " + employee.name +
", Department: " + department.departmentName);
}
}
}
In this example, the Department
class has a list of Employee
objects, representing a one-to-many association. The Department
class can associate with multiple Employee
objects through the addEmployee()
method. The Employee
objects, in turn, can belong to only one Department
. This relationship represents an association between the Department
and Employee
classes.