Java Reference
In-Depth Information
Anonymous classes
Because anonymous classes have no names, the names of the class files that
represent them are an implementation detail. The Oracle/OpenJDK javac uses
numbers to provide anonymous class names (e.g., EnclosingType$1.class ).
Local classes
A local class is named according to a combination (e.g., EnclosingType$1Mem
ber.class ).
Let's also take a quick look at some implementation details of how javac provides
synthetic access for some of the specific cases that nested types need.
Nonstatic member class implementation
Each instance of a nonstatic member class is associated with an instance of the
enclosing class. The compiler enforces this association by defining a synthetic field
named this$0 in each member class. This field is used to hold a reference to the
enclosing instance.
Every nonstatic member class constructor is given an extra parameter that
initializes this field. Every time a member class constructor is invoked, the compiler
automatically passes a reference to the enclosing class for this extra parameter.
Local and anonymous class implementation
A local class is able to refer to fields and methods in its containing class for exactly
the same reason that a nonstatic member class can; it is passed a hidden reference to
the containing class in its constructor and saves that reference away in a private
synthetic field added by the compiler. Like nonstatic member classes, local classes
can use private fields and methods of their containing class because the compiler
inserts any required accessor methods.
What makes local classes different from member classes is that they have the ability
to refer to local variables in the scope that defines them. The crucial restriction on
this ability, however, is that local classes can reference only local variables and
parameters that are declared final . The reason for this restriction becomes appa‐
rent in the implementation.
A local class can use local variables because javac automatically gives the class a
private instance field to hold a copy of each local variable the class uses.
The compiler also adds hidden parameters to each local class constructor to initial‐
ize these automatically created private fields. A local class does not actually access
local variables but merely its own private copies of them. This could cause inconsis‐
tencies if the local variables could alter outside of the local class. 3
3 We will have more to say on this subject when we discuss memory and mutable state in Chap‐
ter 6 .
Search WWH ::

Custom Search