According to JLS: -
8.1.3 Inner Classes and Enclosing Instances
An inner class is a nested class that is not explicitly or implicitly
declared static. Inner classes may not declare static initializers
(§8.7) or member interfaces. Inner classes may not declare static
members, unless they are compile-time constant fields (§15.28).
Any local variable, formal method parameter or exception handler
parameter used but not declared in an inner class must be declared
final. Any local variable, used but not declared in an inner class
must be definitely assigned (§16) before the body of the inner class.
Apart from these two things, which I found important.. There are many more that you can get it from there.. There is a huge explanation about inner classes
, anonymous inner classes
, and nested classes
..
UPDATED EXPLANATION : -
Just think about it. Static block is executed during class initialization, and you cannot initialize a non-static inner class without having an instance of the enclosing class, that's the reason.
Inner classes are associated with the instance
of the enclosing class.. They are like other instance attributes of the enclosing class.. Now, it doesn't make sense to embed a static
field in a non-static
context.. However, if you declare them as Compile Time Constants they would be allowed.
NOTE: - static final Object = null
is not compile time constants.. So, you can't have them inside your inner class
On the other hand, had your inner class been static
, that is actually a nested class, then you can declare your field static, as they will still be associated with the class, so you can access them even before enclosing class in instantiated..
I hope that makes sense..
UPDATE 2 : -
public class A {
class B {
static int x = 0;
}
}
In the above code, static variable x
will be common for every instance of class B..
Also, each instance of class A
, will have it's own copy of class B
(Since JVM will have to load class B every time an instance of A
is created)..
So, static variable x
could not have been shared between every instance of class A
, unless it is a compile time constants.. (To make it more straight foreward: - You can do - B.x
if you see B as outer class.. But class B is itself different for each instance of class A. So, B.x
will be different for each instance of class A.. So, static variable x
is not actually shared between different instances of class A.. Doesn't make sense for a static variable.)
I hope now, that makes sense..