First I wanted to ask Why does Java prohibit static fields in inner classes?, but the question is already there. The reason I gave for needing them (serialVersionUID) was eliminated by the answer by Bozho. However, I’m still curious:
Are static fields prohibited only in the source code or also in the class file?
Btw., a convincing reason why this is prohibited is yet to be invented. In C there are static variables allowed even inside of functions. Their lifespan is the same as of any other static variable, just their visibility is different. The same would work in Java, too.
Nothing really bad would happen if they were design to allow static stuff. There is no problem at class file level, I think, the byte code has no concept of inner class.
It would be confusing though:
Intuitively,
y2andy3should share the samez, but should it be the samezseen byy1?Conceptually an inner class is only valid within the outer instance. It’s even imaginable that JVM unloads it when the outer instance is GC’ed; the argument given in [1] against class unloading doesn’t apply, because inner classes have no static variable or static initializer.
Yet the reality is, there is one class shared by all inner instances, regardless of outer instances. This is certainly true:
y1.getClass()==y2.getClass()==y3.getClass().It can be argued that the language spec dictates that it be true: [2]
y1’s class and y2’s class have the same class loader, the the binary name of X.Y is well defined and independent of outer instance. So y1 and y2 must have the same runtime class.
If the language spec actually implied that an inner class is independent of the outer instance, the generally accepted explanation against static state in inner classes is weakened.
[1] http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.7
[2] http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3.4