The following does not compile, giving an '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, the following does compile:
class InstanceInitialisation1 {
{
System.out.println("Test string is: " + this.testString);
}
private String testString;
public static void main(String args[]) {
new InstanceInitialisation1();
}
}
But the following does not compile, giving an 'illegal forward reference' message:
class InstanceInitialisation2 {
private String testString1;
{
testString1 = testString2;
}
private String testString2;
public static void main(String args[]) {
new InstanceInitialisation2();
}
}
Why do StaticInitialisation and InstanceInitialisation2 not compile, while InstanceInitialisation1 does?
This is covered by section 8.3.3 of the JLS:
In your second case, the use isn't a simple name - you've got
this
explicitly. That means it doesn't comply with the second bullet in the second list quoted above, so there's no error.If you change it to:
... then it won't compile.
Or in the opposite direction, you can change the code in the static initializer block to:
Odd, but that's the way it goes.