Such as:
public class innerclassdemo{
int x;
Class a{
static int a = 0;//is not legal to write this way.
static final int b=0;//It's legal to write this.
}
}
Answer: to put it simply, define a static domain or method that requires a static environment or a top-level environment, where the static environment specifically says that if you add static Class A In your example, you're OK.
A non-static inner class is dependent on an outer class object, and the static domain/method is not dependent on the object-it is only related to the class, so a static domain/method cannot be defined in a non-static inner class and cannot be compiled.
Constants are available (whether or not static) because Java determines all constants at compile time and puts them into so-called constant pools. The mechanism of constants is different from normal variables.
To go into the Java class load order, load the class first, execute the static variable initialization, and then execute the creation of the object, if we are going to execute the variable int a initialization in the code, you must first execute the load external class, then load the inner class, and finally initialize the static variable A, The problem is that in loading the inner class, we can think of the inner class as a non- static member of the outer class, whose initialization must be done after the outer class object is created, and the inner class must be completed after the instantiation of the instance. The Java virtual machine requires that all static variables be completed before the object is created, thus creating a contradiction.
And the Java constant in the memory of the constant pool, its mechanism and variables are different, at compile time, load constants do not need to load the class, so there is no such contradiction.
Why can't there be static variables in the Java non-static inner class and can have constants?