[英]Java immutable class doubt
I am writing a immutable class.One of the instance is an object of another class which is mutable.How can i prevent the modification of the state of that instance. I am writing a immutable class.One of the instance is an object of another class which is mutable.How can i prevent the modification of the state of that instance.
If you provide delegates to all the getters, but don't provide a getter for the field itself.如果您为所有 getter 提供代表,但不为字段本身提供 getter。 For example:
例如:
public final class Foo {
private Bar bar;
public String getBarField1() {
return bar.getBarField1();
}
public String getBarField2() {
return bar.getBarField2();
}
}
But there is a thing to consider - how is the field created.但是有一点需要考虑——该字段是如何创建的。 If it is passed in constructor, then you have to create a copy of it rather than get the passed object, otherwise the creating code will have reference to the
Bar
instance and be able to modify it.如果在构造函数中传入,则必须创建它的副本而不是获取传递的 object,否则创建代码将引用
Bar
实例并能够对其进行修改。
getVarNameProperty1()
, getVarNameProperty2()
);getVarNameProperty1()
, getVarNameProperty2()
) 访问变量的字段;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.