A member class is a class that is declared as a non-static member of a containing class. If a static member class is analogous to a class field or class method, a member class is analogous to an instance field or instance method. Example 3-9 shows how a member class can be defined and used. This example extends the previous LinkedStack example to allow enumeration of the elements on the stack by defining an enumerate() method that returns an implementation of the java.util.Enumeration interface. The implementation of this interface is defined as a member class.
Example 3-9. An Enumeration Implemented as a Member Class
public class LinkedStack {
// Our static member interface; body omitted here...
public static interface Linkable { ... }
// The head of the list
private Linkable head;
// Method bodies omitted here
public void push(Linkable node) { ... }
public Linkable pop() { ... }
// This method returns an Enumeration object for this LinkedStack
public java.util.Enumeration enumerate() { return new Enumerator(); }
// Here is the implementation of the Enumeration interface,
// defined as a member class.
protected class Enumerator implements java.util.Enumeration {
Linkable current;
// The constructor uses the private head field of the containing class
public Enumerator() { current = head; }
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null) throw new java.util.NoSuchElementException();
Object value = current;
current = current.getNext();
return value;
}
}
}
Notice how the Enumerator class is nested within the LinkedStack class. Since Enumerator is a helper class used only within LinkedStack, there is a real elegance to having it defined so close to where it is used by the containing class.