Nested class types |
Usage and remark |
Advantage |
Disadvantage |
static member classes |
Use for public helper class, useful only in conjunction with its outer class. (Such as the operation types of a Calculater). |
Save memory. Class specific. |
Not instance specific. |
nonstatic member classes |
Define an Adapter that allows an instance of outer class to be viewed as an instance of some unrelated class.(Such a simple mentations 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) The association between a nonstatic member class instance and its enclosing instance is established when the former is created; it cannot be modified thereafter. It is possible, although rare, to establish the association manually using the expression enclosingInstance.new MemberClass(args). |
Instance specific. |
Adds time to its construction since initialization of the nested class for each instance. |
anonymous classes |
|
No name. |
|
local classes |
A local class can be declared anywhere a local variable can be declared and obeys the same scoping rules. Local classes have attributes in common with each of the other kinds of nested classes. |
|
|
// 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>{
...
}
}
Note
If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration.
Summary
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.
Effetive Java 22 Favor static member classes over nonstatic,布布扣,bubuko.com