java多态的理解

来源:互联网 发布:计算机专业不喜欢编程 编辑:程序博客网 时间:2024/05/18 01:06

下面的代码相信很多人都看过,但是很多人并不知道具体的原理。。。所以把我的理解记录下来,供大家参考。。
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{}

class E

{

  public static void main(String [] args) {   A a1 = new A();   A a2 = new B();   B b = new B();   C c = new C();   D d = new D();   System.out.println(a1.show(b));   //①   System.out.println(a1.show(c));   //②   System.out.println(a1.show(d));   //③   System.out.println(a2.show(b));   //④   System.out.println(a2.show(c));   //⑤   System.out.println(a2.show(d));  // ⑥   System.out.println(b.show(b));    //⑦   System.out.println(b.show(c));    //⑧   System.out.println(b.show(d));    //⑨     }

}

(三)答案

         ①   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

首先a1是一个A类对象,当调用a1.show(b)方法时,我们发现A类中没 有对象,所以这时可以调用a1.show(a)方法,打印出”A and A”,同理,a1.show(c)也是打印出”A and A”,对于a1.show(d),A中存在对象为D的show方法,所以直接调用,打印出”A and D”。
b和a2大致相同,只是b所属的类含有show(B b)方法。
按照this.show(o)->super(this).show(o)->this.(super(o))->super.this.(super(o))的顺序来进行多态调用方法的排序

0 0
原创粉丝点击