简体   繁体   中英

Why would you use private static inner class? Defeats the purpose of static inner class?

I've read all the articles I could find on static inner classes, and from what I understand:

  • An instance of a static inner class can be created without previously creating the outer class. This is one main difference between static and non-static inner classes.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM