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() {
                foo(MyClass.this);
            }
        };
    }
}

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 Reply

Your email address will not be published. Required fields are marked *