Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2044674
  • 博文数量: 519
  • 博客积分: 10070
  • 博客等级: 上将
  • 技术积分: 3985
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-29 14:05
个人简介

只问耕耘

文章分类

全部博文(519)

文章存档

2016年(1)

2013年(5)

2011年(46)

2010年(220)

2009年(51)

2008年(39)

2007年(141)

2006年(16)

我的朋友

分类: Java

2010-01-14 14:10:36

难以理解的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,不存在“上去造型,下来执行”的问题
 */
 
 
阅读(542) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~