Java Reference
In-Depth Information
Features of local classes
Local classes have the following interesting features:
• Like member classes, local classes are associated with a containing instance and
can access any members, including private members, of the containing class.
• In addition to accessing fields defined by the containing class, local classes can
access any local variables, method parameters, or exception parameters that are
in the scope of the local method definition and are declared final .
Restrictions on local classes
Local classes are subject to the following restrictions:
• The name of a local class is defined only within the block that defines it; it can
never be used outside that block. (Note, however, that instances of a local class
created within the scope of the class can continue to exist outside of that scope.
This situation is described in more detail later in this section.)
• Local classes cannot be declared public , protected , private , or static .
• Like member classes, and for the same reasons, local classes cannot contain
static fields, methods, or classes. The only exception is for constants that are
declared both static and final .
• Interfaces, enumerated types, and annotation types cannot be defined locally.
• A local class, like a member class, cannot have the same name as any of its
enclosing classes.
• As noted earlier, a local class can use the local variables, method parameters,
and even exception parameters that are in its scope but only if those variables
or parameters are declared final . This is because the lifetime of an instance of
a local class can be much longer than the execution of the method in which the
class is defined.
A local class has a private internal copy of all local variables it
uses (these copies are automatically generated by javac ). The
only way to ensure that the local variable and the private copy
are always the same is to insist that the local variable is final .
Scope of a local class
In discussing nonstatic member classes, we saw that a member class can access any
members inherited from superclasses and any members defined by its containing
classes. The same is true for local classes, but local classes can also access final local
Search WWH ::

Custom Search