[英]Java: Get super class from an anonymous class
在Java中,我在扩展B的类A中使用匿名类。如何从该匿名类访问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");
}
}
在run
,您可以将foo()
更改为B.super.foo();
当我更改它然后运行B.bar()
我得到了Good
。
在这种情况下,您需要this
进行限定才能捕获外部类B
B.this.foo()
或者,根据您的需要,使用超级类
B.super.foo()
Java语言规范的相关部分:
请致电休假:
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.