Reputation: 53
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.
Upvotes: 1
Views: 858
Reputation: 1321
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.
Upvotes: 3
Reputation: 393836
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.
Upvotes: 6