11.1.2. Nested Generic Types
A nested type can also be declared as a generic type with its own type variables. Because static members
cannot refer to type variables of their own class, any type variable in a static nested type is distinct from any
type variable in the outer type, even if they have the same name. For example, if Cell objects are only
intended for use within SingleLinkQueue objects, then it would be reasonable for Cell to be a static
nested class within SingleLinkQueue:
class SingleLinkQueue
static class Cell
private Cell
private E element;
public Cell(E element) {
this.element = element;
}
public Cell(E element, Cell
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
/ ... rest of Cell methods as before ... /
}
protected Cell
protected Cell
/ ... rest of SingleLinkQueue methods as before ... /
}
The code in Cell and SingleLinkQueue is unchanged except that Cell is declared as a static nested
class within SingleLinkQueue. The type variable E is used for both classes because the element type of a
cell must always match the element type of the queue it is part of, but they are distinct names. The two
different E types are associated in the declarations of head and tail, where the E type parameter of the
SingleLinkQueue class defines the parameterized type Cell
carefully and avoid confusion. If the type variables should always represent the same type then use the same
name; if they can be distinct types, then use different names.
If the nested type is an inner class, then the type variables of the outer class declaration are accessible to it and
can be used directly. For example, an alternative design of the queue could use a non-generic inner class to
define cell objects:
class SingleLinkQueue
class Cell {
private Cell next;
private E element;
public Cell(E element) {
this.element = element;
}
public Cell(E element, Cell next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
/ ... rest of Cell methods ... /
}