Java Reference
In-Depth Information
A nonstatic member class, like any member of a class, can be assigned one of the
standard access control modifiers. In Example 4-2 , the LinkedIterator class is
declared protected , so it is inaccessible to code (in a different package) that uses
the LinkedStack class but is accessible to any class that subclasses LinkedStack .
Restrictions on member classes
Member classes have two important restrictions:
• A nonstatic member class cannot have the same name as any containing class
or package. This is an important rule, one that is not shared by fields and meth‐
ods.
• Nonstatic member classes cannot contain any static fields, methods, or types,
except for constant fields declared both static and final .
static members are top-level constructs not associated with
any particular object while every nonstatic member class is
associated with an instance of its enclosing class. Defining a
static top-level member within a member class that is not at
the top level would cause confusion, so it is not allowed.
m
e
Syntax for member classes
The most important feature of a member class is that it can access the instance
fields and methods in its containing object. We saw this in the LinkedStack.Linked
Iterator() constructor of Example 4-2 :
public LinkedIterator () { current = head ; }
In this example, head is a field of the enclosing LinkedStack class, and we assign it
to the current field of the LinkedIterator class (which is a member of the non‐
static member class).
If we want to use explicit references, and make use of this , then we have to use a
special syntax for explicitly referring to the containing instance of the this object.
For example, if we want to be explicit in our constructor, we can use the following
syntax:
public LinkedIterator () { this . current = LinkedStack . this . head ; }
The general syntax is classname .this , where classname is the name of a contain‐
ing class. Note that member classes can themselves contain member classes, nested
to any depth. However, because no member class can have the same name as any
containing class, the use of the enclosing class name prepended to this is a perfectly
general way to refer to any containing instance.
Search WWH ::




Custom Search