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?
The compiler complains (in the constructor), because you already provide an initialization by writing
remove the ‘
= null‘ part. Addfinaland assign the value in the constructor.