Java Reference
In-Depth Information
The language does not prevent you from deeply nesting classes, but
good taste should. A doubly nested class such as
Z
has three name
scopes: itself, its immediate enclosing class
Y
, and outermost class
X
.
Someone reading the code for
Z
must understand each class thoroughly
to know in which context an identifier is bound and which enclosing ob-
ject was bound to which nested object. We recommend nesting only one
level under most circumstances. Nesting more than two levels invites a
readability disaster and should probably never be attempted.
5.2.2. Extending Inner Classes
An inner class can be extended just as any static nested class or top-
level class can. The only requirement is that objects of the extended
class must still be associated with objects of the original enclosing class
or a subclass. Usually this is not a problem because the extended inner
class is often declared within an extension of the outer class:
class Outer {
class Inner { }
}
class ExtendedOuter extends Outer {
class ExtendedInner extends Inner { }
Inner ref = new ExtendedInner();
}
The
ref
field is initialized when an
ExtendedOuter
object is created. The
creation of the
ExtendedInner
instance uses the default no-arg construct-
or of
ExtendedInner
, which in turn implicitly invokes the default no-arg
constructor of
Inner
by using
super
. The constructor for
Inner
requires an
object of
Outer
to bind to, which in this case is implicitly the current ob-
ject of
ExtendedOuter
.
If the enclosing class of the inner subclass is not a subclass of
Outer
, or
if the inner subclass is not itself an inner class, then an explicit referen-