java - why illegal forward reference error not shown while using static variable with class name -


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 static variables declared in it. @ point, variable a has got memory allocated (declaration done)
  • then static initializers run in order of occurrence.
    • first statement sysout(a);. a hasn't been initialized yet, can't access it. (error)
    • second statement a = 99. here you're initializing variable a. fine.
    • third 1 sysout(test.a) - reasoning posted above. compiler knows test loaded.
    • then static int = 10 executed. re-initializes a 10. remember, declaration part taken care of in first step.

Comments