I know the meaning of nested static classes, but found it confusing sometimes deciding when to declare them over non static nested classes.
Is it mainly when instantiation wouldn't be a good sense?
What are the general rules of thumb helping you decide when to use static modifier?
This is a very interesting question. I would try to explain it to you.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
Basically, a static nested class interacts with the instance members of its top-level class, just like any other classes.
So, basically you can and should consider a static nested class as a top-level class which has been nested inside another top-level class just for packaging convenience.
So whenever you are using a nested class, start by making it static, and then see if you need to access any instance members thereby having an opportunity to make it non-static.
Take the example from JDK,
public class LinkedList<E> ... {
...
private static class Entry<E> { ... }
}
Here, the Entry
is a static nested class as it doesn't make any sense for this class to be a top-level class as it is used by the LinkedList
class only. And since it doesn't even use any members of the LinkedList
class, thus making is static makes even more sense.