Java Reference
In-Depth Information
The introduction of local classes confuses the picture, however. To see why, notice
that instances of a local class can have a lifetime that extends past the time that the
JVM exits the block where the local class is defined.
In other words, if you create an instance of a local class, that
instance does not automatically go away when the JVM fin‐
ishes executing the block that defines the class. So, even
though the definition of the class was local, instances of that
class can escape out of the place they were defined.
This can cause effects that some developers initially find surprising. This is because
local classes can use local variables, and so they can contain copies of values from
lexical scopes that no longer exist. This can been seen in the following code:
public class Weird {
// A static member interface used below
public static interface IntHolder { public int getValue (); }
public static void main ( String [] args ) {
IntHolder [] holders = new IntHolder [ 10 ];
for ( int i = 0 ; i < 10 ; i ++) {
final int fi = i ;
// A local class
class MyIntHolder implements IntHolder {
// Use the final variable
public int getValue () { return fi ; }
}
holders [ i ] = new MyIntHolder ();
}
// The local class is now out of scope, so we can't use it. But we
// have 10 valid instances of that class in our array. The local
// variable fi is not in our scope here, but it is still in scope
// for the getValue() method of each of those 10 objects. So call
// getValue() for each object and print it out. This prints the
// digits 0 to 9.
for ( int i = 0 ; i < 10 ; i ++) {
System . out . println ( holders [ i ]. getValue ());
}
}
}
To make sense of this code, remember that the lexical scope of the methods of a
local class has nothing to do with when the interpreter enters and exits the block of
code that defines the local class.
Each instance of a local class has an automatically created private copy of each of
the final local variables it uses, so, in effect, it has its own private copy of the scope
that existed when it was created.
Search WWH ::




Custom Search