Java initializes outer class static field when that class is interacted with, but does not initialize nested static class field.
So I have read the nested class documentation: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html and I think it comes down to this line here:
In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
If my understanding is correct that means that java views my two classes below as separate entities;
public class OutterClass {
private static final OutterClass outterField = new OutterClass("outterField");
private OutterClass(String string) {
System.out.println(string + " has been initialised");
}
private static class InnerClass {
private static final OutterClass innerField = new OutterClass("innerField");
}
public static void foo() {}
}
Meaning that when I interact with the OuterClass by calling the Outer.foo(), java will initialize my static field as it is part of the OuterClass. But since it views the InnerClass as a separate top level class, InnerClass's fields don't get initialized.
1) Is my understanding correct?
2) Has this got anything to do with the JIT compiler or the class loader? Is the InnerClass loaded when the OuterClass is loaded?
Thanks
InnerClassandOuterClass. It makes a lot more sense now why theInnerClass.innerFieldis not initialized as it is physically in a separate file.