例:
package jvm;
class DynamicDispatch {
static abstract class Human {
protected abstract void sayHello();
}
static class Man extends Human {
@Override
protected void sayHello() {
System.out.println("man say hello");
}
}
static class Women extends Human {
@Override
protected void sayHello() {
System.out.println("women say hello");
}
}
public static void main(String[] args) {
Human man = new Man();
Human women = new Women();
man.sayHello();
women.sayHello();
man = new Women();
man.sayHello();
}
}
运行结果:
man say hello
women say hello
women say hello
我们把这种在运行期根据实际类型确定方法执行版本的分派过程称为动态分派。