我试图通过使其成为最终类来使以下类中的实例变量不可变..但似乎我可以修改它的数据..只有引用不可变吗?(即我不能将另一个 Y 实例分配给该变量?)
public class StateModification {
private final Y immutable ;
public StateModification() {
super();
this.immutable = new Y(100);
}
public void setImmutableData(int x){
this.immutable.setYnum(x);
}
public int getImmutableData(){
return this.immutable.getYnum();
}
public static void main(String[] args) {
StateModification sm = new StateModification();
System.out.println("immutable="+sm.getImmutableData());
sm.setImmutableData(222);
System.out.println("immutable="+sm.getImmutableData());
}
}
class Y{
private int ynum;
public Y(int ynum) {
super();
this.ynum = ynum;
}
public int getYnum() {
return ynum;
}
public void setYnum(int ynum) {
this.ynum = ynum;
}
}
o/p
不可变=100
不可变=222