publicclassDynamicDispatch{staticabstractclassHuman{protectedabstractvoidsayHello();}staticclassManextendsHuman{@OverrideprotectedvoidsayHello(){System.out.println("man say hello");}}staticclassWomanextendsHuman{@OverrideprotectedvoidsayHello(){System.out.println("woman say hello");}}publicstaticvoidmain(String[] args){Human man =newMan();Human woman =newWoman();
man.sayHello();// invokevirtual #22; //Method org/fenixsoft/polymorphic/DynamicDispatch$Human.sayHello:()V
woman.sayHello();// invokevirtual #22; //Method org/fenixsoft/polymorphic/DynamicDispatch$Human.sayHello:()V
man =newWoman();
man.sayHello();}}//运行结果:
man say hello
woman say hello
woman say hello
分析:
Human man = new Man();中的“Human”称为变量的“静态类型”也即父类对象,后面的“Man”则被称为变量的“实际类型”也即子类对象;