问题描述
要使一个类不可变,我能做的是:
To make a class immutable what I can do is:
1)使类最终
2)不提供setter
3)将所有变量标记为final
1)Make class final
2)do not provide setters
3)mark all variables as final
但是如果我的类有另一个类的其他对象那么,somone可以更改该对象的值
But if my class has another object of some other class then , somone can change value of that object
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?
}
}
推荐答案
A)使 OtherClass
不可变
或
B)不允许直接访问 OtherClass
对象,而只提供getter充当代理。
B) Don't allow direct access to the OtherClass
object, instead providing only getters to act as a proxy.
编辑添加:您可以制作 OtherClass的深层副本
并返回一个副本而不是原始副本,但这通常不是您在Java中所期望的行为类型。
Edit to add: You could make a deep copy of OtherClass
and return a copy rather than the original, but that generally isn't the type of behavior you would expect in Java.
这篇关于在java中使类不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!