假设我有一个定义如下的 Employee 类:
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;
...
}
在上面的代码中,考虑到 Address 对象可以用 setter 改变,Employee 真的是不可变的吗?如果不是,我们是否应该 clone() Employee 返回原来的 Employee?...
最佳答案
如果您的 Address
类具有使其可变的 setter ,那么不,我会说 Employee
不是不可变的,因为它包含的地址可以更改。
关于Java:复合对象的不变性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9501769/