Re: Usefulness of "final" (Was: Re: Inserting In a List)
On Wednesday, April 3, 2013 6:46:35 PM UTC-7, markspace wrote:
Lew wrote:
public class ImmutableA
{
private final String ident = "Immutable instance";
}
Now 'ImmutableA' instances are immutable. Not only that, but in this cas=
e, because
'ident' is 'final' and initialized by a constant expression, it is now a=
constant variable.
And because String itself is immutable.
I said "and initialized by a constant expression", which is a stronger asse=
rtion than immutability.
It encompasses immutability, so the fact that String is immutable is covere=
d by my comment.
public class NotImmutable {
public final char[] string = {'a','b','c'};
}
final, public, initialized by a constant expression, but not immutable.
It is *not* initialized by a constant expression!
I should have given the full term, a "compile-time constant expression" (JL=
S =A715.28):
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28
"A compile-time constant expression is an expression denoting a value of pr=
imitive type or a String that does not complete abruptly and is composed us=
ing only the following: [list of restricted syntax] ..."
The restricted syntax allows only certain expressions involving primitives =
or 'String's.
An array is neither primitive nor a 'String'.
This is also immutable:
public class ImmutableB {
public final String string = "abc";
}
'string' is also a constant variable.
Can't change it, so it's OK to be public. Thread safe immutable.
Furthermore, it's a constant variable, so its visibility is different that =
it would be without 'final'.
Also, simply referencing a static constant variable does not invoke initial=
ization of its containing class.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1
(See my post to Eric, what the JLS actually says in section 17.5 is
"thread safe immutable [sic]", which is rather different from just
"immutable." I've been confusing the two terms in my posts when I
really should not. What I've really been talking about I should call
"thread safe immutable" to match the JLS.)
All "thread-safe immutable" means is immutable and not seen by another thre=
ad until after the
immutability is assured by a memory barrier.
--
Lew