I've read all the articles I could find on static inner classes, and from what I understand:
But none of the articles answer this question:
Why would you have a private static inner class, if the purpose of having a static inner class is so that you can create it without the outer class?
For example, Java's LinkedList implementation contains the private static class Node<E>
. If we try instantiating LinkedList<String>.Node<String>
it won't work since it's private. And I don't see why you would want to create a Node without a LinkedList either, since you just use the LinkedList's add() interface. So can't this just be a non-static inner class?
For me it seems like private and static for inner classes are contradictory, and if you want to be both private and static that's weird. So could someone please explain what I'm missing?
Thanks!
Remember that an non-static nested class ("inner class") instance has a reference to its containing instance. That isn't free. If you don't need it, you shouldn't have it.
LinkedList
is an excellent example of exactly why you'd have a static
nested class: LinkedList
needs multiple instances of LinkedList.Node
, and it doesn't need those instances to have a reference to the list itself. That would be pointless overhead. So the Node
class is static
in order not to have those back references to the list. It's also private
because it's only for internal use by LinkedList
.
Side note on terminology: There is no "static inner class" in Java. If it's static
, it's not an inner class, it's a static nested class. More in the tutorial.