Gonen I :
Why does this code compile with explicit static field notation on the right hand side, but not without ?
public class A
{
static int a = ++A.a; // compiles
//static int a = ++a; // error - cannot reference a field before it is defined
public static void main(String[] args) {
System.out.println(a);
}
}
Andy Turner :
This is simply how the language spec is written. Specifically, Sec 8.3.3 says:
References to a field are sometimes restricted, even through the field is in scope. The following rules constrain forward references to a field (where the use textually precedes the field declaration) as well as self-reference (where the field is used in its own initializer).
For a reference by simple name to a class variable f declared in class or interface C, it is a compile-time error if:
- ...
Emphasis mine.
A.a
is not a simple name, so it's not a compile-time error.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=443178&siteId=1