Static Member Class
One common use of a static member class is as a public helper class, useful only in conjunction with its outer class.
For example, consider an enum describing the operations supported by a calculator (Item 30). The
Operation
enum should
be a public static member class of the
Calculator class. Clients of
Calculator could then refer to operations using names like
Calculator.Operation.PLUS
and Calculator.Operation.MINUS.
Syntactically, the only difference between static and nonstatic member classes is that static member classes have the modifier
static
in their declarations.Despite the syntactic similarity, these two kinds of nested classes are very different. Each instance of a nonstatic member class is implicitly associated with an enclosing
instance of its containing class. Within instance methods of a nonstatic member class, you can invoke methods on the enclosing instance or obtain a reference to the enclosing
instance using the qualified this
construct [JLS, 15.8.4]. If an instance of a nested class can exist in isolation from an instance of its enclosing class, then the nested class
must be a static member class: it is impossible to create an instance of a nonstatic member class without an enclosing
instance.
None Static Member Class
One common use of a nonstatic member class is to define an
Adapter [Gamma95, p. 139] that allows an instance of the outer class to be viewed as an instance of some unrelated class. For example, implementations of the
Map
interface typically use nonstatic member classes to implement their
collection views, which are returned by
Map’s
keySet,
entrySet, and
values
methods. Similarly, implementations of the collection interfaces, such as
Set
and List, typically use nonstatic member classes to implement their iterators:
// Typical use of a nonstatic member class
public class MySet<E> extends AbstractSet<E> {
... // Bulk of the class omitted
public Iterator<E> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<E> {
...
}
}
To
recap, there are four different kinds of nested classes, and each has its place. If a nested class needs to be visible outside of a single method or is too long to fit comfortably inside a method, use
a member class. If each instance of the
member class needs a reference to its enclosing instance, make it nonstatic; otherwise, make it static. Assuming the class belongs inside a method, if you need to create instances from only one location
and there is a preexisting type that characterizes the class, make it an anonymous class; otherwise, make it a local class.