Is it possible to make a variable final
in any given moment?
I would like to decide when its immutable, not just with the first assignment.
It would be perfect, if null
would not count as an assignment. So if you would initialize it with null, you would still have a wildcard for the first assignment after some code, not necessarily in the constructor.
Once you assign a final
variable, you can never change its value, as stated here:
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable.
If you want to have a variable which at a given point in time can be made immutable, what you can do is something like so:
...
private boolean isMutable;
private String someString;
public void setMutable(boolean value)
{
this.isMutable = value;
}
public void setSomeString(String value)
{
if (this.isMutable)
{
this.someString = value;
}
}
...
No you cannot. What you can do is encapsulating it withing a method:
public boolean setValue(int i)
{
if(isMutable)
{
value = i;
return true;
}
return false;
}
It should be done when the variable is being declared, therefore it is not possible to make an already declared variable final
.
Just for you to know, the feature is now proposed in a draft: http://openjdk.java.net/jeps/309. It's called dyanmic constant. Check future work section:
The value is, therefore, dynamic but, since its value is only set once, it is also constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With