java : accessing static variables inside static block -
analyzing weird scenario in following static block :
static { system.out.println("inside static block"); i=100; // compilation successful , why ? system.out.println(i); // compilation error "cannot reference field before defined" } private static int i=100;
while same code working fine while using :
static { system.out.println("inside static block"); i=100; // compilation successful , why ? system.out.println(myclass.i); // compiles ok } private static int i=100;
not sure why variable initialization not need variable access using class name while sop requires ?
this because of restrictions on use of fields during initialization. in particular, use of static fields inside static initialization block before line on declared can on left hand side of expression (i.e. assignment), unless qualified (in case myclass.i
).
so example: if insert int j = i;
right after i = 100;
same error.
the obvious way solve issue declare static int i;
before static initialization block.
Comments
Post a Comment