You can initialize like the following but it is considered bad practice in multi-threading applications but sometimes acceptable for specific use cases in single thread applications. One important thing to consider is if you pass the Department object as this
to the Employee object technically the object is not fully constructed. Another thing to consider is how garbage collection will function in such a pattern.
public class Department {
List<Employee> myEmployeeList;
public Department() {
int size = 5;
myEmployeeList.add(new Employee(this));
}
}
public class Employee {
Department myDepartment;
public Employee(Department department) {
myDepartment = department;
}
}
You could also have a class that holds references to both Department
and Employee
and give Employee
that reference. Or initialize Department
in a method from Employee
.