Java Reference
In-Depth Information
5.3. Local Inner Classes
You can define inner classes in code blocks, such as a method body, con-
structor, or initialization block. These local inner classes are not members
of the class of which the code is a part but are local to that block, just as
a local variable is. Such classes are completely inaccessible outside the
block in which they are definedthere is simply no way to refer to them.
But instances of such classes are normal objects that can be passed as
arguments and returned from methods, and they exist until they are no
longer referenced. Because local inner classes are inaccessible, they can't
have access modifiers, nor can they be declared static because, well,
they are local inner classes. All of the other class modifiers, including
annotations, can be applied, though only strictfp and annotations have
practical applications.
A local inner class can access all the variables that are in scope where
the class is definedlocal variables, method parameters, instance variables
(assuming it is a non-static block), and static variables. The only restric-
tion is that a local variable or method parameter can be accessed only
if it is declared final . The reason for this restriction relates mainly to
multithreading issues (see Chapter 14 ) and ensures that all such vari-
ables have well-defined values when accessed from the inner class. Given
that the method accessing the local variable or parameter could be in-
voked after the completion of the method in which the local class was
definedand hence the local variables and parameters no longer existthe
value of those variables must be frozen before the local class object is
created. If needed, you can copy a non-final variable into a final one that
is subsequently accessed by the local inner class.
Consider the standard interface Iterator defined in the java.util package.
This interface defines a way to iterate through a group of objects. It is
commonly used to provide access to the elements in a container object
but can be used for any general-purpose iteration:
package java.util;
public interface Iterator<E> {
boolean hasNext();
 
Search WWH ::




Custom Search