Java 超类引用子类对象的示例代码
动态方法分配 dynamic method dispatch
一个被重写的方法的调用会在运行时解析,而不是编译时解析
Java 会根据在调用发生时引用的对象的类型来判断所要执行的方法
public class DynamicMethodDispatch {
void callSubClassMethod(subDynamicMethodDispatch d) {
System.out.println("Call from SuperClass");
d.subClassMethod();
System.out.println("END CALL");
}
public static void main(String[] args) {
DynamicMethodDispatch dispatch = new DynamicMethodDispatch();
dispatch.callSubClassMethod(new subDynamicMethodDispatch());
dispatch = new subDynamicMethodDispatch();
dispatch.callSubClassMethod(dispatch);
}
}
class subDynamicMethodDispatch extends DynamicMethodDispatch {
void subClassMethod() {
System.out.println("Method from subclass.");
}
}