I have a couple of questions relating to nested classes within Java.
-
How do nested classes appear “under the hood”, with regards to memory allocations?
-
You cannot declare a static variable within a nested class (I think the exact error was that static attributes can only be declared at the top level class). Why is this and what other restrictions are there for nested classes?
If possible, please say whether your answer is Java-specific, or whether C++ also follows the same rules?
Inner classes are exactly the same as regular classes as far as memory and compilation are concerned. (Perhaps there is some difference in the way they’re managed in memory, but it’s not visible to the average Java developer) In fact, when you compile a class that has an inner class, you can see the compiled .class file as
OuterClass$InnerClass.class. So as far as I know, the JVM treats them the same.As far as static variables are concerned, I’m not certain what the issue is. For example, this runs for me:
EDIT
As Jeffery pointed out, this does NOT compile:
The difference is, I had the first static variable listed as final.
After thinking about this awhile, I agree with @Eugene. They allow static fields on inner classes to be
finalbecause then there’s no problem with initialization. The value cannot change, you just initialize it to its value. If, however, the static field is notfinal, you then require an instance of the outer class to be created in order to initialize the field, and static members can’t be tied to particular instances.I found this discussion on it as well.