Java Reference
In-Depth Information
Local Classes
A local class isaclassthatisdeclaredanywherethatalocalvariableisdeclared.Fur-
class has a name and can be reused. Like anonymous classes, local classes only have
enclosing instances when used in nonstatic contexts.
A local class instance can access the surrounding scope's local variables and para-
final . For example, Listing 3-12 ' s local class declaration accesses a final parameter
and a final local variable.
Listing 3-12. Declaring a local class
class EnclosingClass
void m(final int x)
final int y = x*2;
class LocalClass
int a = x;
int b = y;
LocalClass lc = new LocalClass();
Listing3-12 declares EnclosingClass withitsinstancemethod m() declaringa
local class named LocalClass . This local class declares a pair of instance fields ( a
and b )thatareinitializedtothevaluesof final parameter x and final localvariable
y when LocalClass isinstantiated: new EnclosingClass().m(10); ,forex-
Listing 3-13 demonstrates this local class.
Listing 3-13. Demonstrating a local class
Search WWH ::

Custom Search