假设我有这三个类:
class Foo {
void fn() {
System.out.println("fn in Foo");
}
}
class Mid extends Foo {
void fn() {
System.out.println("fn in Mid");
}
}
class Bar extends Mid {
void fn() {
System.out.println("fn in Bar");
}
void gn() {
Foo f = (Foo) this;
f.fn();
}
}
public class Trial {
public static void main(String[] args) throws Exception {
Bar b = new Bar();
b.gn();
}
}
是否可以调用 Foo
的 fn()
?我知道我在 gn()
中的解决方案不起作用,因为 this
指向 Bar
类型的对象。
最佳答案
这在 Java 中是不可能的。您可以使用 super
,但它始终使用类型层次结构中直接父类(super class)中的方法。
另请注意:
Foo f = (Foo) this;
f.fn();
是 polymoprhism 虚拟调用如何工作的定义:即使 f
是 Foo
类型,但在运行时 f .fn()
被分派(dispatch)到 Bar.fn()
。编译时类型无关紧要。
关于java - 我可以从 super 的 super 调用重写的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281057/