[英]Java - Any way to make variable unmodifiable after being set in the constructor?
I have a member variable that in a class that I want to make sure nothing changes it after it is set in the constructor. 我有一个成员变量,在类中我想确保在构造函数中设置后没有任何更改。 So, it would look something like this:
所以,它看起来像这样:
public class MyClass
{
private String myVar = null;
public MyClass(DataObj dataObj)
{
myVar = dataObj.getFinalVarValue();
//at this point I don't want anything to be able change the value of myVar
}
....
}
My first thought was to see I could just add the final
modifier to the variable, but the compiler complains about assigning a value to the final field. 我的第一个想法是看到我可以将
final
修饰符添加到变量中,但编译器抱怨为最终字段赋值。 Is it possible to accomplish this? 有可能做到这一点吗?
The compiler complains (in the constructor), because you already provide an initialization by writing 编译器抱怨(在构造函数中),因为您已经通过编写提供了初始化
private String myVar = null;
remove the ' = null
' part. 删除'
= null
'部分。 Add final
and assign the value in the constructor. 添加
final
并在构造函数中指定值。
public class MyClass
{
private final String myVar;
public MyClass(DataObj dataObj)
{
myVar = dataObj.getFinalVarValue(); // the only assignment/init happens here.
}
....
}
Make it private
, and then don't include a setter. 将其设为
private
,然后不包含setter。 As long as you never change it in within the class methods, it's immutable. 只要你在类方法中永远不改变它,它就是不可变的。
String objects are already immutable. 字符串对象已经是不可变的。 So adding the private final modificator is enough.
因此添加私有最终修改器就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.