The JLS, Section 8.3.3, gives the rules for giving a compiler error for a forward reference.
For a reference by simple name to an instance variable f
declared in class C
, it is a compile-time error if:
The reference appears either in an instance variable initializer of C
or in an instance initializer of C
(§8.6); and
The reference appears in the initializer of f
's own declarator or at a point to the left of f
's declarator; and
The reference is not on the left hand side of an assignment expression (§15.26); and
The innermost class enclosing the reference is C
.
There is no provision for a compiler error for a reference from a nested or inner class. Curiously, a non-simple reference can gain access to a forward reference, e.g.
this.x++;
Also, later on in that same section, there is an example that explicitly states that access from a different class is ok.
class UseBeforeDeclaration {
// Snipped
{
// Snippped
j = j + 1;
// error - right hand side reads before declaration
// Snipped
Object o = new Object() {
void foo(){ j++; }
// ok - occurs in a different class
{ j = j + 1; }
// ok - occurs in a different class
};
}
// Snipped
int j;
}
I've only included the relevant parts -- the instance initializer that makes a forward reference using an inner class, plus the declaration at the end.