Java:从匿名类中获取超类(Java: Get super class from an anonymous class)

在Java中,我在A类中使用了一个匿名类,它扩展了B.如何从这个匿名类访问B? 我不能使用关键字super ,因为这意味着匿名类的 超类 ,而不是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 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"); } }

最满意答案

请致电休闲:

B.super.foo();

在此更改后, B类看起来如下:

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

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

更多推荐