Ram swaroop Ram swaroop - 5 months ago 23
Java Question

Method local inner class vs inner class

The below code produces the output

middle
. Can anyone explain in detail how this is happening?

Is it because the declaration of "inner" version of
class A
comes after the instance of
class A
is created in the
go()
method?

class A {
void m() {
System.out.println("outer");
}
}

public class MethodLocalVSInner {
public static void main(String[] args) {
new MethodLocalVSInner().go();
}

void go() {
new A().m();
class A {
void m() {
System.out.println("inner");
}
}
}

class A {
void m() {
System.out.println("middle");
}
}
}

Answer

I guess you expected the local class method to be invoked. That didn't happen, because you're using new A() outside the scope of local class. So, it accesses the next closer candidate in scope, that would be the inner class. From JLS §6.3:

The scope of a local class declaration immediately enclosed by a block (ยง14.2) is the rest of the immediately enclosing block, including its own class declaration.

Thus, new A() in the first line of method, will not access the local class appearing after it. If you move the class declaration before that, you'll get the expected output.

Also see JLS §14.3, which contains similar example.