Non-static vs Static Nested class
A class can be defined within another class. These classes are known as nested classes. They allow you to logically group related classes in one place.
A non-static nested class has full access to enclosing class’s member variables. non-static nested class is called inner class.
According to Effective Java
Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class… It is possible to invoke methods on the enclosing instance.
A static nested class does not have access to the nested class.
Non-static nested class
1 | class OuterClass { |
To instantiate an inner class, you must first instantiate the outer class.
1 | OuterClass.InnerClass innerObj = outerObj.new InnerClass(); |
But inside the enclosing class, you don’t need the prefix
1 | NestedClass nc = new NestedClass(); |
Non-static nested class has access to the enclosing class.
1 | class OuterClass { |
Static nested class
there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class.
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.
1 | class OuterClass { |
You don’t need a outer class to create a static nested class. To instantiate a static nested class
1 | OuterClass.NestedClass in = new OuterClass.NestedClass(); |
If there is no need to directly create an instance of the nested class, you can use a static nested class. For example, LinkedList class has a static nested class Entry.
1 | public class LinkedList<E> ... { |