I'm trying to better understand the concept of anonymous classes in Java. From other answers on this website, I learned that an anonymous class can access non-final fields of the enclosing class using OuterClass.this.myField
.
I made the following simple test case with an interface, AnonInt
, and a class AnonTest
with a method foo
which returns an instance of an anonymous class implementing AnonInt
. Dspite the fact that I'm using System.out.println(a)
rather than System.out.println(AnonTest.this.a)
the code works and prints the correct result. How can this be?
public interface AnonInt {
void print();
}
public class AnonTest {
private int a;
public AnonTest(int a) {
this.a = a;
}
public AnonInt foo() {
return new AnonInt() {
public void print() {
System.out.println(a);
}
};
}
public static void main(String[] args) {
AnonTest at = new AnonTest(37);
AnonInt ai = at.foo();
ai.print();
}
}