java - 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; = 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 case 1 cause compilation error?
the jls holds answer (note bold statement):
similarly, every blank final variable must assigned @ once; must definitely unassigned when assignment occurs. such assignment defined occur if , if either simple name of variable (or, field, simple name qualified this) occurs on left hand side of assignment operator. [§16]
this means 'simple name' must used when assigning static final variables - i.e. var name without qualifiers.
Comments
Post a Comment