public class MyClass {
public int myclassMember=NestedClass.nestedclassMember; //Compiler error,static reference to a non-static field
public static class NestedClass {
public int nestedclassMember=myclassMember; //Compiler error,static reference to a non-static field.
public NestedClass() {
}
}
}
But at the same time,the following is totally legal,after removing the compile-time errors of course -:
MyClass.NestedClass nestedInstance= new MyClass.NestedClass();
What gives?How can the class be both static and non static at the same time?
staticdoesn’t mean the same thing in this context as what it means for fields and methods.A static nested class is a class that doesn’t need any outer class instance to be created.
A non-static nested class needs an instance of its outer class to be created, and has an implicit reference to this instance (available using
TheNameOfTheOuterClass.thisinside the inner class).Static inner classes are typically used to avoid exposing classes to the outside when they’re used only by one class, or to have a class being able to access private fields and methods of an outer class, or to scope a class to another one, because it’s tightly linked to it.