java - Why can't we set the value of static final variable in static block through class name -
this question has answer here:
for example, consider code snap below:
public static final int a; public static final int b; static { = 8; // it's working test.b = 10; // compilation error test.b cannot assigned. }
why can't use test.b = 10;
inside static block of test
class itself? without class name it's working fine.
is there reason behind this?
a static final variable must initialized before use. may initialized either directly @ declaration time, or in static block.
but when use class.var = x
not seen initialization assignation.
with jdk 7, error cannot assign value final variable.
that explains why works if remove final
keyword
class test { static final int = 2; // initialization @ declaration time static final int b; static final int c; static { b = 4; // initialization in static block test.c = 6; // error : cannot assign value final variable c } ... }
edit
in jls correct word initialization definite assignement
extract jls :
for every access of local variable or blank final field x, x must assigned before access, or compile-time error occurs.
similarly, every blank final variable must assigned @ once; must unassigned when assignment occurs.
such assignment defined occur if , if either the simple name of variable (or, field, simple name qualified this) occurs on left hand side of assignment operator.
for every assignment blank final variable, variable must unassigned before assignment, or compile-time error occurs.
emphasize mine, think real reason error.
Comments
Post a Comment