JLS states that "Inner classes may not declare static members, unless they are constant variables". The reason behind this prohibition is that a class variable in an object-dependent class has high potential for creating confusion.
Consider a simple example:
class Parent {
public class Child {
static int count = 1; // Let's pretend that it is possible
public void increment() {
count++;
}
public void show() {
System.out.println(count);
}
}
public Child generateChild() {
return new Child();
}
}
Now let's say we do this:
Parent p1 = new Parent();
Parent.Child c1 = p1.generateChild();
Parent p2 = new Parent();
Parent.Child c2 = p2.generateChild();
c2.show();
c1.increment();
c2.show();
An increment on a child of parent 1 causes a change in a child of a different parent, even though a Child
class is attached to its Parent
class, so children of different parents should have independent contexts.
Java language designers reasoned that if you indeed want this behavior, you would have no problem putting the static variable in the parent class.