首页 > 编程知识 正文

java多态的理解简单易懂,java中多态性的概念

时间:2023-05-06 05:27:09 阅读:203995 作者:4938

下面的代码相信很多人都看过,但是很多人并不知道具体的原理。。。所以把我的理解记录下来,供大家参考。。
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))的顺序来进行多态调用方法的排序

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。