I read this question about immutable objects and was left with a question regarding immutable objects and final field:
Why do we need instance variable in immutable class to be final?
For example, consider this immutable class:
public final class Immutable
{
private final int someVal;
public Immutable(int someVal)
{
this.someVal= someVal;
}
public int getVal() {
return val;
}
}
If in the above code there is no set methods and the instance variable is set only within the constructor, why is it required that the instance variable is declared final?
There is no requirement as such to make the variable final
. However, when it is true that you explicitly intend to never change the variable, it is often good practice to make it final
, since that not only enforces the invariant against typos or other mistakes, but also declares the intent that it be immutable to, eg., other programmers or yourself.
If the variable were public
, then you would strictly need to make it final
in order to ensure that interfacing code cannot change its value.
Do note that the question you link is not directly related, however, as it discusses classes that are final
, rather than variables. Making a class final
means that it cannot be inherited from, not that it is immutable. There is certainly a case to be made for taking heed of the contents of that question and its answer when making immutable objects, however; but it is a separate question nonetheless.