next up previous
Next: Spaghetti References (akin Up: 2.1.4 Mutable Sequences Previous: Extended Mutable Lists: Nested Classes vs. Inner Classes

A nested class is a class whose definition appears inside the definition of another class, as if it were a member of the other class. For example, if a program contains

class A {
  class B {
    // fields, methods of class B...
  // fields, methods of class A...
then class B is a nested class of class A. Code outside of the methods of class A can refer to class B by calling it A.B, using the same dot notation as for field and method references. Within the methods of class A class B can be used without qualifying the name. B could be hidden from code outside of class A by declaring it private, just as with fields and methods.

A nested class like B is known as an inner class. An inner class has access to the fields of an instance of its enclosing class. For this reason, an instance of B can only be created in association with an instance of A, using the expression

/it A.B(...)
outside of A's methods, where instanceA is an instance of A, and
new B(...)
inside of A's methods. The new instance of B also knows about the enclosing instance of A, and can refer to it using the expression
We can think of an instance of an inner class as having two this pointers, one for itself and one for its enclosing instance. An inner class may be nested within another inner class, so an inner class can even have multiple levels of this pointers. A nesting depth more than one level is quite uncommon, however, and should usually be avoided.

A nested class can be declared static, in which case it has reduced access to its enclosing class. For example, if B were declared static above, it could no longer access the instance variables of A, and there would be no associated instance A.this. Static nested classes are known as nested top-level classes, because they are exactly like classes declared outside any other class, except for the way they are named. Instances of a static nested class are created using regular new, as in

new A.B(...)

We'll see uses for both static nested classes and inner classes when we present the full implementation of imperative lists.

next up previous
Next: Spaghetti References (akin Up: 2.1.4 Mutable Sequences Previous: Extended Mutable Lists:
Corky Cartwright