Anonymous classes: references to parents

If you want to create an anonymous class (here: inherited frow OtherClass) and you need a reference to the containing class (here: MyClass), you should do it as follows:

class MyClass {
    void myProcedure() {
        OtherClass oc = new OtherClass() {
            void otherProcedure() {

It is much easier to use “MyClass.this” than to introduce a line like “final MyClass selfref = this;” outside of the anonymous class and finally call “foo(selfref);”

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.