- A Concurrent Affair - https://www.concurrentaffair.org -

Anonymous Inner Class Surprise

I had no idea that the following code was allowed:

public class AICSurprise {
public static void main(String[] args) {
new Object() {
public void foo() { System.out.println("foo"); }
}.foo();
}
}

I thought foo() could not be accessed from outside the class, because the class was an anonymous extension of Object. That’s demonstrated here:

public class AICSurprise {
public static void main(String[] args) {
Object o = new Object() {
public void foo() { System.out.println("foo"); }
};
o.foo(); // error
}
}

Note that Object is the most precise type we can give for o. Somehow there are special rules for accessing an anonymous inner class directly when it is being created.

Did you know this? After working with Java for nearly ten years, I still didn’t.

[1] [2]Share [3]