FinalReferenceImpliesImmutability
Misconception:
If a final variable refers to an object, that object is immutable.
Incorrect
An object referred to by a final variable is an immutable object
Correct
An object referred to by a final variable can be a mutable object
CorrectionHere is what's right.
Here is what's right.
Assume this class:
class Counter {
private int count;
public void increment() {
count++;
}
}
And assume this variable:
final Count c = new Count();
The object pointed to by c
is not immutable!
The state of the object can change, e.g. by calling c.increment()
.
What cannot change is the value of variable c
:
that variable is final
and thus will always refer to the same object.
We cannot assign anything else to c
,
so c
can never point to a different object.
But the object it points to may change its state.
Language
Java