I tried writing this up with my own words, but the SCJP 6 book does it way better, so here it goes:
A static nested class is simply a class that's a static member of the enclosing class
Perhaps to better understand, here's some code:
public class HolaMundo {
public static class AnotherClass {
public void hello(){
System.out.println("Hello");
}
public static void hola(){
System.out.println("Hola");
}
}
public static void main(String[] args) {
HolaMundo.AnotherClass.hola();
HolaMundo.AnotherClass holaAnother = new HolaMundo.AnotherClass();
holaAnother.hello();
}
}
Note that the above code in the main()
method will continue to work if you remove the occurrences of HolaMundo.
.
If you're confused, here's more from the book:
The class itself isn't really "static"; there's no such thing as a static class. The static modifier in this case says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class.
A static
method (like main()
), doesn't belong (and also cannot access) to any particular instance of any class.
This means that a static method can create new instances of any class it has access to, even if it happens to be an instance of the class that declared said method in the first place.
Now, since in this case, main()
, AnotherClass
and method()
are all static members of HolaMundo
, then yes, this means that they all "run together".
More specifically, they are loaded when the class is first loaded by the JVM (aka at Class Loading time).