Reputation: 40337
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. Is it possible to accomplish this?
Upvotes: 3
Views: 1660
Reputation: 1349
String objects are already immutable. So adding the private final modificator is enough.
Upvotes: -1
Reputation: 1938
The compiler complains (in the constructor), because you already provide an initialization by writing
private String myVar = null;
remove the '= null
' part. Add final
and assign the value in the constructor.
public class MyClass
{
private final String myVar;
public MyClass(DataObj dataObj)
{
myVar = dataObj.getFinalVarValue(); // the only assignment/init happens here.
}
....
}
Upvotes: 14
Reputation: 2698
Make it private
, and then don't include a setter. As long as you never change it in within the class methods, it's immutable.
Upvotes: 1