1、Why isn't a qualified static final variable allowed in a static initialization block?
case 1:
class Program {
static final int var;
static {
Program.var = 8; // Compilation error
}
public static void main(String[] args) {
int i;
i=Program.var;
System.out.println(Program.var);
}
}
case 2:
class Program {
static final int var;
static {
var = 8; //OK
}
public static void main(String[] args) {
System.out.println(Program.var);
}
}
Why does Case 1 cause a compilation error?
Answer:
The JLS holds the answer (note the bold statement):
Similarly, every blank final variable must be assigned at most once; it must be definitely unassignedwhen an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple name qualified by this) occurs on the left hand side of an assignment operator. [§16]
This means that the 'simple name' must be used when assigning static final variables - i.e. the var name without any qualifiers.
But :static class A
{
static final int a;
static
{
// System.out.println(a); // illegal
System.out.println(A.a); // compiles!
a = 1;
}
}
(From stackoverflow)