Sle*_*idi 3 java polymorphism inheritance dynamic-binding
假设我有这三个类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能调用Foo的fn()?我知道我的解决方案gn()不起作用,因为this它指向一个类型的对象Bar.
这在Java中是不可能的.您可以使用super但它始终在类型层次结构中使用立即超类中的方法.
另请注意:
Foo f = (Foo) this;
f.fn();
Run Code Online (Sandbox Code Playgroud)
是多态性的定义,虚拟调用f是如何工作的:即使是类型Foo,但在运行时f.fn()被调度到Bar.fn().编译时类型无关紧要.