Suppose I’ve an Employee class with below definition:
class Employee {
private final String id;
private final String name;
private final String dept;
private final Address address;
public Employee(String id, String name, String dept, Address address) {
this.id = id;
this.name = name;
this.dept = dept;
this.address = address;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDept() {
return dept;
}
public Address getAddress() {
return address;
}
}
class Address {
private String addrLine1;
private String addrLine2;
...
}
In above code, is Employee really immutable given that Address object can be changed with setters? If not, should we clone() Employee to return original Employee?…
You need to clone() the mutable object which is Address. cloning Employee won’t help.