简体   繁体   中英

Java - set object attribute to null

I try to implement an specification diagram. There are 3 classes: Company, Department, Employee.

  • Employee has name, salary, department.
  • Every Department has a Company, name, employees (0..n) - I made a LinkedList for that -, and a Manager of the Employee Type which can be manager in only one department.
  • Departments can have subdepartments of the Department Type - I made a LinkedList for that, too. And a "different" constructor for subdepartments.

  • Every Company has a name.

Now I have a questions and an issue:

  • QUESTION: Since a manager can be manager in only one department, I check in setManager if any department has this manager as manager. If so, then I return. Is this a correct way to do this? I thought about a boolean isManager but there's nothing like that in the specification.
  • ISSUE: If I remove an Employee from a departments list with removeEmployee I set the Department variable of the Employee in the same method to null. But if I try to get the name of the Department in which the Employee is, I still get the Department and not null.

That's how the removeEmployee of the Department class code looks like:

public void removeEmployee(Employee e) {  
    employees.remove(e);  
    e.setDepartment(null);  
}

In the main method I do this to check if the Department of the Employee is null:

    departmentName.employees.remove(employeeName);
    System.out.println(employeeName.getDepartment().getName());

The Output should be null , but I get departmentName . He's removed from the employees list of the Department but to set the Department of the Employee to null fails.

I would be happy if you could answer my question and help me with my issue.

I could also upload the diagram and my three classes to let you check but I don't think you want to waste your time.

Kind regards, Newb

It appears that employees is some sort of List<Employee> and is public .

This makes it possible to call departmentName.employees.remove(employeeName); which does not call setDepartment(null) , it would be better to declare employees as private , and only use the public removeEmployee() method to remove the employees.

This way you avoid removing employees in any other way than the way you've defined (this is called encapsulation).

I suggest to replace line with invoking remove method, because you don't invoke your method. Instead of that you invoke Collection method.

It should looks like this:

ObjectName.removeEmployee(employee);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM