roipoussiere
roipoussiere

Reputation: 5956

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");
    }
}

Upvotes: 1

Views: 622

Answers (3)

Sanjeev Saha
Sanjeev Saha

Reputation: 2652

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");
    }
}

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298918

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:

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201447

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

Upvotes: 3

Related Questions