Anonymous Inner Class Surprise

I had no idea that the following code was allowed:

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
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.

Share

About Mathias

Software development engineer. Principal developer of DrJava. Recent Ph.D. graduate from the Department of Computer Science at Rice University.
This entry was posted in Ramblings. Bookmark the permalink.

Leave a Reply