initialization of final fields
Martyn Pearce
m.pearce@inpharmatica.co.uk
Thu Nov 4 06:24:00 GMT 1999
| > Pathological example I know, but... I don't think we've covered the
| > possibility that a given initializer calls such a method more than
| > once.
| >
| > Actually, I don't think it's so patholgical --- the method call might be
| > embedded in a loop without thinking.
Jerry Kramskoy writes:
| Sun's stated semantics for writes to final fields are weaker than your
| proposal ...
| the current class (to which the executing method belongs)
| must be the same as the declaring class for the final field.
I think we're at cross purposes here. I'm not thinking of which class
the call is coming from, but how many times:
class MyClass
{
final int widget;
int[] bar;
public
MyClass (int count)
{
bar = new int[count];
for (int i = 0; i < count; i++)
this.init (i);
}
private void
init (int foo)
{
bar[foo] = 1;
widget = foo;
}
}
Which is illegal (not to mention odd), since widget gets assigned to
more than once, but I think that the scheme proposed by Per doesn't
catch this.
I hasten to add that I don't suppose it'll occur that often, and that
Per's scheme is several steps ahead of Sun's --- last I checked, jdk
javac still can't handle indirect assignments to final fields (i.e.,
assignments from methods called by the c'tor). Neither does jikes.
Mx.
PS: If there's still confusion about which part of the JLS is referred
to here, the reader is directed to
http://java.sun.com/docs/books/jls/html/1.1Update.html
D.1.2 New Uses for final
Paragraph 3:
'You can defer initialization of a final field or variable, as long as
you initialize it before it is used and assign a value to it exactly
once. The compiler will check for proper assignment, as will the
verifier before code is executed.'
More information about the Java
mailing list