Alexandre Vandermonde Alexandre Vandermonde - 2 months ago 10
Java Question

Surprising access to fields with Java anonymous class

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();
}
}

Answer

Despite 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?

Since the reference to a is unambiguous in your context, the two expressions reference the same field.

Generally, AnonTest.this is required in a very specific context - when your method needs to access AnonTest object itself, rather than accessing one of its members. In case of your program, this is unnecessary: the compiler resolves the expression a to the object AnonTest.this.a, and passes it to System.out.println.

Comments