假设我们有一个类:
class A {
public void m() {
System.out.println("A - > m()");
}
}
...我想在类创建时覆盖方法m
而不创建第二个子类B
来扩展A
。
public static void main(String[] args) {
A a = new A() {
@Override
public void m() {
System.out.println("Override - > m()");
new Thread(new Runnable() {
@Override
public void run() {
// I want to be able to call the super method.
// This is illegal!
A.super.m();
}
}).start();
}
};
a.m();
}
目前我的解决方案是创建一个调用 super.m()
A a = new A() {
private void superMethod() {
super.m();
}
@Override
public void m() {
System.out.println("Overrided - > m()");
new Thread(new Runnable() {
@Override
public void run() {
superMethod();
}
}).start();
}
};
a.m();
我想知道为什么我不能编写 A.super.m()
以及是否有其他方法可以执行此任务。
最佳答案
I want to know why I am not able to write
A.super.m()
...
这是因为 A
实际上不是一个直接封闭的类。 Runnable
的直接封闭类是new A() { ... }
这是 A
的匿名子类.
换句话说,如果你有
class A extends Base {
new Runnable() { ... }
}
然后 A.super
会工作,但现在你有
class <Anonymous subclass of A> extends A {
new Runnable() { ... }
}
这意味着类似 A.super
的东西不可能,因为 <Anonymous subclass of A>.super.m
没有语法.
...and, is there another way to perform this task.
我认为你解决问题的方式是合理的。另一种方法是创建 A
的本地子类(只是为了引入一个在 ____.super.m
中使用的标识符)如下:
public static void main(String[] args) {
class SubA extends A {
@Override
public void m() {
System.out.println("Override - > m()");
new Thread(new Runnable() {
@Override
public void run() {
SubA.super.m();
// ^^^^ we now have a name of the directly enclosing class
}
}).start();
}
}
A a = new SubA();
a.m();
}
关于java - 从重写方法内的匿名内部类中调用 super 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148424/