难以理解的Java 运行时多态Runtime Polymorphism, 经过一些尝试,总结出 基本原则:“上去造型,下来执行”,请看下面示例。
/*
The essence of runtime polymorphic behavior
With runtime polymorphism based on method overriding, the decision as to which version of a method will be executed is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is invoked.
*/
package c1;
class A {
public String show(D obj){
return ("A and D");
}
public String show(A obj){
return ("A and A");
}
}
class B extends A{
public String show(B obj){
return ("B and B");
}
public String show(A obj){
return ("B and A");
}
}
class C extends B{}
class D extends B{}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
A a1 = new A();
A a2 = new B();//upcasting,上去造型,下来执行
B b = new B();
C c = new C();
D d = new D();
System.out.println(a1.show(b)); // 1
System.out.println(a1.show(c)); // 2
System.out.println(a1.show(d)); // 3
System.out.println(a2.show(b)); // 4
System.out.println(a2.show(c)); // 5
System.out.println(a2.show(d)); // 6
System.out.println(b.show(b)); // 7
System.out.println(b.show(c)); // 8
System.out.println(b.show(d)); //9
}
}
/*
输出结果:
A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D
*/
/*
解释:
- 对于1,2,3的输出,类型为A,实例为A,所以跟B没有关系
- 对于4,5,6的输出,类型为A,实例为B,基本原则:上去造型,下来执行。如下:
- 对于4的输出,a2.show(b),因为类型为A,首先上到A类造型:
public String show(A obj){
return ("A and A");
}
然后下到B(因为实例为B)找到重写方法执行,也就是B.show(A obj),千万不要认为会执行B.show(B obj),因为B.show(B obj)在A里没有造型,无论如何也执行不到它
- 对于5的输出, 同4
- 对于6的输出,a2.show(d),因为类型为A,首先上到A类造型:
public String show(D obj){
return ("A and D");
}
然后下到B(因为实例为B),但是在B类找不到重写方法,所以执行A.show(D obj)
-对于7,8,9的输出,类型为B,实例为B,不存在“上去造型,下来执行”的问题
*/
阅读(562) | 评论(0) | 转发(0) |