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:
public class Tester {
public static void main(String[] args) {
System.out.println(InnerTester.MY_STRING);
}
public class InnerTester {
public static final String MY_STRING = "MY_STRING";
}
}
EDIT
As Jeffery pointed out, this does NOT compile:
public class Tester {
public static void main(String[] args) {
System.out.println(InnerTester.MY_STRING);
}
public class InnerTester {
public static String MY_STRING = "MY_STRING";
}
}
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 final
because then there's no problem with initialization. The value cannot change, you just initialize it to its value. If, however, the static field is not final
, 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.