first:
the use of terms:
A nested class is a class which is contained in another class at the source code level.
If you declare it with the static modifier, then its name is static nested class.
A non-static nested class is called inner class.
second:
the key differences between static nested classes and inner classes
static nested classes:
1. They do not have access to the fields and methods of the enclosing class.
2. they can be instantiated without a corresponding instance of the outer class.
inner classes:
1. inner class has an implicit reference to the enclosing class, so they have access to the fields and methods of the enclosing class even if they are declared private.
2. they cannot be instantiated without a corresponding instance of the outer class.
third:
when to use nested classes in general?
if you just want to keep your classes together if they belong typically together or if you need a class that do some functionality that is exclusively related to the outer class, The nesting creates a type of namespace. To denote a nested class from outside its enclosing class, the nested class is prefixed with the name of the enclosing class.
when to use static vs non static?
from an OO design point of view you decide which one to use depending on whether you want your nested class to have access to enclosing class members or no, so ask yourself, does your nested class need that access?
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.
to fully understand the decision rule we can see a practical and real example that is in LinkedList class
note my comments beside the code.
public class LinkedList
{
transient int size = 0;
transient Node
transient Node
...
private class ListItr implements ListIterator
private Node
private Node
private int nextIndex;
private int expectedModCount = modCount;
...
}
private static class Node
E item;
Node
Node
...
}
} //outer class end
references:
Sybex SCJP for Java platform SE6, Richard F. Raposa
http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class
http://stackoverflow.com/questions/253492/static-nested-class-in-java-why
http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html
http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html
nice post
ReplyDeletePython full stack developer course in hyderabad