This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Don't know, but I recommend you do a search for Bruce Eckel's Thinking in Java; the 3rd edition is available free of charge as an HTML document. It has a nice chapter about inner classes. And inner classes are much too difficult for the beginner's forum. Moving.
Joined: Oct 13, 2005
Please read the important administrative private message which I have just sent you.
I think that they chose to make this illegal for two reasons: it's potentially confusing, and it's never necessary. One could argue that Sun has allowed plenty of other things that are potentially confusing and not necessary, but still, they do make some effort to limit such things.
It's potentially confusing because inner classes are often associated with an instance of an outer class. If have two different outer class instances, and a static variable in an inner class inside those instances, should it be possible to have two different values of the static variable? Or just one? Probably just one makes more sense, but the way some people visualize inner classes, two might make sense too.
It's never necessary because you can always simply define the static variable as part of the outer class - either as static in the outside class, or nonstatic if you do want it to have more than one value per outer class instance. There's really no need to attach it to the inner class if it's not an instance variable of that inner class. It's pointless.
To answer the question : Jave follows : Static fields can only be declared in a static or top level types.
you need to either define the static field in the outer class or mark the inner class as static itself.
To discuss: I wonder what purpose a static variable would serve inside an inner class. If you want to keep it static for the instances of outer class, this can be done by static variable in outer class. If you want to keep it static for instances of inner class, this can be done by using a instance variable of outer class. So static variable inside a non-static inner class will be redundant and may be that is reason why Sun intentionally didnt bother to maintain it.