Reputation: 2720
I understand that static variable or method is never garbage collected until the program ends, but how does a static nested class works? I found this quote in the oracle website and I know that a top-level class cannot be static so a nested static class will behave as a non-static class. But it does not ensure me if it will also be garbage collected in the same way.
A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Upvotes: 2
Views: 1893
Reputation: 1503944
An instance of a static nested class will be eligible for garbage collection when there are no GC roots which still refer to it - just like any other object.
The class itself will be eligible for garbage collection when the classloader which loaded it is eligible for garbage collection - just like any other class.
Even inner classes behave the same way - the implicit reference is from the inner class instance to an instance of the enclosing class... so an instance of the inner class can "secretly" prevent an instance of the enclosing class from being garbage collected, but not the other way round. (Obviously an instance of the enclosing class could have a reference to an instance of the inner class, but only explicitly.)
Upvotes: 9