use*_*796 7 java object immutability
为了使类不可变,我能做的是:
1)使类最终
2)不提供setter
3)将所有变量标记为final
但是如果我的类有另一个类的其他对象,那么somone可以改变该对象的值
class MyClass{
final int a;
final OtherClass other
MyClass(int a ,OtherClass other){
this.a = a;
this.other = other;
}
int getA(){
return a;
}
OtherClass getOther(){
return other;
}
public static void main(String ags[]){
MyClass m = new Myclass(1,new OtherClass);
Other o = m.getOther();
o.setSomething(xyz) ; //This is the problem ,How to prevent this?
}
}
Run Code Online (Sandbox Code Playgroud)
A)OtherClass也使不可变
或者
B) 不允许直接访问对象OtherClass,而只提供 getter 来充当代理。
编辑添加:您可以制作深层副本OtherClass并返回副本而不是原始副本,但这通常不是您在 Java 中期望的行为类型。