简体   繁体   中英

Java: Get super class from an anonymous class

In Java, I use an anonymous class inside a class A which extends B. How can I access to B from this anonymous class? I can't use the keyword super , because this means super class of the anonymous class , not super class of A .

public class A {

    void foo() {
        System.out.println("Good");
    }
}

public class B extends A {

    void bar() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                foo(); // Bad: this call B.foo(), not A.foo()
                // super.foo(); // Bad: "Method foo is undefined for type Object"
            }

        };
        r.run();
    }

    @Override
    void foo() {
        System.out.println("Bad");
    }
}

In run , you could change foo() to B.super.foo(); when I changed that and then ran B.bar() I get Good .

In such a case, you need to qualify this to capture the outer class, B

B.this.foo()

Or, in your case, as you want the super class, use

B.super.foo()

Relevant parts of Java Language Spec:

Please call as fallows:

B.super.foo();

After this change B class looks as follows:

public class B extends A {

    public static void main(String[] args) {
        new B().bar();
    }

    void bar() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                B.super.foo(); // this calls A.foo()
            }

        };
        r.run();
    }

    @Override
    void foo() {
        System.out.println("Bad");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM