Objects in an immutable class as member variable

余生颓废 提交于 2020-01-05 12:10:14

问题


I have a class X which holds Employee object. I want to make the class X as immutable. Now even if I declare the Employee object as final the Employee class exists independently and people can access the setter methods of that particular employee object. Is it possible to have a normal class Employee and another immutable class X which holds Employee but we cannot change value of Employee once it is assigned?

public final class X {

private final Employee emp;

public X (Employee e){
   this.emp = e;

}
public Employee getEmp(){

return emp;

}

} 

The employee class I dont want to make it immutable, just want to make the class X as immutable.Hence once an employee is assigned it should not be allowed to change it. Is that possible without making the class Employee as immutable. I want class Employee to exist independently so do not want to privatize its construction.


回答1:


You don't have to expose the Employee member of the immutable class. You can introduce getter methods that would expose only relevant fields of the Employee.

public final class X {

  private final Employee emp;

  public X (Employee e){
     this.emp = e.clone ();
  }

  public String getEmpName(){
    return emp.getName();
  }

  public int getEmpSalary(){
    return emp.getSalary();
  }

} 

Of course, there's one more thing you have to do to ensure the class is really immutable. The constructor should create a copy of the Employee passed to it. Otherwise, the caller of the constructor would still have a reference to the Employee, and would be able to change that object.




回答2:


You could add an copy constructor to Employee and use it whenever an instance of it is passed into or out of your immutable class.

public final class X {

    private final Employee emp;

    public X (Employee e){
       this.emp = new Employee(e);

    }
    public Employee getEmp(){
      return new Employee(emp);
    } 
} 

Having said this, you should still seriously re-evaluate if you better would make Employee immutable, too, as all this copying could have quite some overhead.



来源:https://stackoverflow.com/questions/24984890/objects-in-an-immutable-class-as-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!