in below code while access static variable class name not showing forward reference error access without class name shows error. why doesn't happens accessing class name?
class test{ static { system.out.println(a); // shows error = 99; // , line doesn't gives error system.out.println(test.a); // line doesn't } static int = 10; static{ system.out.println(a); } }
the rules forward reference defined in jls §8.3.3:
use of class variables declarations appear textually after use restricted, though these class variables in scope (§6.3). specifically, compile-time error if of following true:
the declaration of class variable in class or interface c appears textually after use of class variable;
the use simple name in either class variable initializer of c or static initializer of c;
the use not on left hand side of assignment;
c innermost class or interface enclosing use.
so, first sysout(), satisfies above 4 conditions, , hence it's compile time error.
in 2nd sysout(), you're accessing a using it's qualified name, rather simple name, per above rules allowed.
now, reason be, when access test.a, compiler sure test class has been loaded , static fields have been initialized, can access field a. while accessing a on simple name, compiler isn't sure initializer a has run or not, since might still in process of loading class.
consider following process of loading of class:
- when class loaded, memory allocated
staticvariables declared in it. @ point, variableahas got memory allocated (declaration done) - then
staticinitializers run in order of occurrence.- first statement
sysout(a);.ahasn't been initialized yet, can't access it. (error) - second statement
a = 99. here you're initializing variablea. fine. - third 1
sysout(test.a)- reasoning posted above. compiler knowstestloaded. - then
static int = 10executed. re-initializesa10. remember, declaration part taken care of in first step.
- first statement
Comments
Post a Comment