I'm just getting up to speed on Java, and have a question about local class
behavior. Here's a mini-app to illustrate:
interface Foo { void print(); }
class LocalClassTest
{
public static void main(String[] args) {
Foo foo = getFooImpl(100);
foo.print();
}
public static Foo getFooImpl(final int i) {
class FooImpl implements Foo {
public void print() {
System.out.println("i = " + i);
}
}
return new FooImpl();
}
}
As expected (at least, as I expect) this code prints "i = 100". But what
bugs me is where does this come from? By the time I call "foo.print" the
method "getFooImpl" has returned, and its local variables/parameters should
have been flushed off the stack, along with the value "100" that eventually
gets printed. The only way I can see this as working is that the compiler
has somehow promoted the parameter "i" in "getFooImpl" into a hidden field
within class FooImpl, but I cannot find any docs about this anywhere. Or is
"i" really a reference and has FooImpl grabbed a shadow(y) ref to it?
Any of you experts care to shed some light on this?
Thanks,
Tim