java - Why do two programs have forward referencing errors while the third does not? -


the following not compile, giving 'illegal forward reference' message:

class staticinitialisation {      static     {         system.out.println("test string is: " + teststring);     }      private static string teststring;      public static void main(string args[]) {         new staticinitialisation();     } } 

however, following compile:

class instanceinitialisation1 {      {         system.out.println("test string is: " + this.teststring);     }      private string teststring;      public static void main(string args[]) {         new instanceinitialisation1();     } } 

but following not compile, giving 'illegal forward reference' message:

class instanceinitialisation2 {          private string teststring1;      {         teststring1 = teststring2;     }      private string teststring2;      public static void main(string args[]) {         new instanceinitialisation2();     } } 

why staticinitialisation , instanceinitialisation2 not compile, while instanceinitialisation1 does?

this covered section 8.3.3 of jls:

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.

use of instance variables declarations appear textually after use restricted, though these instance variables in scope. specifically, compile-time error if of following true:

  • the declaration of instance variable in class or interface c appears textually after use of instance variable;

  • the use simple name in either instance variable initializer of c or instance initializer of c;

  • the use not on left hand side of assignment;

  • c innermost class or interface enclosing use.

in second case, use isn't simple name - you've got this explicitly. means doesn't comply second bullet in second list quoted above, there's no error.

if change to:

system.out.println("test string is: " + teststring); 

... won't compile.

or in opposite direction, can change code in static initializer block to:

system.out.println("test string is: " + staticinitialisation.teststring); 

odd, that's way goes.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -