I was looking at the Java code for LinkedList
and noticed that it made use of a static nested class, Entry
.
public class LinkedList<E> ... {
...
private static class Entry<E> { ... }
}
What is the reason for using a static nested class, rather than an normal inner class?
The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation.
But I thought there might be other reasons, maybe performance. What might it be?
Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
Best Answer
The Sun page you link to has some key differences between the two:
There is no need for
LinkedList.Entry
to be top-level class as it is only used byLinkedList
(there are some other interfaces that also have static nested classes namedEntry
, such asMap.Entry
- same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.As Jon Skeet points out, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.