Re: Usefulness of "final" (Was: Re: Inserting In a List)
markspace wrote:
final is necessary. It is not sufficient (you also have to not mutate
the object in question after the enclosing object's ctor exits). I'm
pretty sure the field must also be explicitly private. (Implicitly
Nope.
You can have immutable public fields.
might not be enough to satisfy what ever escape analysis the Java
compiler does.)
'final' is essential to the definition of constant variables, which do have special
initialization semantics.
'final' is an essential piece in locking down an immutable reference variable of a type; call
this type 'ImmutableA'.
The object referenced by the member is immutable by dint of its implementation, which
we'll postulate to be correct.
public class ImmutableA
{
private String ident = "Immutable instance";
}
While the object referenced by 'ident' is immutable, this is not enough to make instances
of 'ImmutableA' immutable. For that you must have 'final'.
public class ImmutableA
{
private final String ident = "Immutable instance";
}
Now 'ImmutableA' instances are immutable. Not only that, but in this case, because
'ident' is 'final' and initialized by a constant expression, it is now a constant variable.
So 'final' is most assuredly involved in creating immutability, and is more reliable in the
face of refactoring and other maintenance to preserve it than immutability idioms that
do not use 'final'.
--
Lew