Java经验杂谈(2.对Java多态的理解)

时间:2021-03-27 16:10:53

多态是面向对象的重要特性之一,我试着用最简单的方式解释Java多态:

要正确理解多态,我们需要明确如下概念:
・定义类型和实际类型
・重载和重写
・编译和运行

其中实际类型为new关键字后面的类型。

重载发生在编译阶段,由定义类型决定。
重写发生在运行阶段,由实际类型决定。

确定a.fun(b)最终调用了哪个类的哪个方法,可以通过如下几步进行:
1.运用继承规则,确定每个类具有的全部方法,包括父类的方法;
2.运用重载规则,确定编译阶段对应的定义类型的方法;
3.运用重写规则,确定运行阶段对应的实际类型的方法;
注:重写规则如果找不到同名同参同参同参的方法,则调用父类同名同参同参同参的方法。与重载规则无关无关无关。

我们做一道经典题,代码如下:

 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...{}

问题:以下输出结果是什么?

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,B拥有的全部方法;(C,D略)
A:
--show(D obj)→"A and D"
--show(A obj)→"A and A"
B:
--show(D obj)→"A and D"
--show(B obj)→"B and B"
--show(A obj)→"B and A"

步骤二,运用重载规则,调用关系如下:(确定调用哪个方法)
① a1.show(b)⇒A.show(B→A)
② a1.show(c)⇒A.show(C→B→A)
③ a1.show(d)⇒A.show(D)
④ a2.show(b)⇒A.show(B→A)
⑤ a2.show(c)⇒A.show(C→B→A)
⑥ a2.show(d)⇒A.show(D)
⑦ b.show(b)⇒B.show(B)
⑧ b.show(c)⇒B.show(C→B)
⑨ b.show(d)⇒B.show(D)
步骤三,在步骤一的基础上,继续运用重写规则,确定调用关系,并且应用步骤一的方法:(确定哪个类调用)
① a1.show(b)⇒A.show(A)⇒A.show(A):输出"A and A"
② a1.show(c)⇒A.show(A)⇒A.show(A):输出"A and A"
③ a1.show(d)⇒A.show(D)⇒A.show(D):输出"A and D"
④ a2.show(b)⇒A.show(A)⇒B.show(A):输出"B and A"
⑤ a2.show(c)⇒A.show(A)⇒B.show(A):输出"B and A"
⑥ a2.show(d)⇒A.show(D)⇒B.show(D):输出"A and D"
⑦ b.show(b)⇒B.show(B)⇒B.show(B):输出"B and B"
⑧ b.show(c)⇒B.show(B)⇒B.show(B):输出"B and B"
⑨ b.show(d)⇒B.show(D)⇒B.show(D):输出"A and 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

版权声明:本教程版权归java123.vip所有,禁止任何形式的转载与引用。

原帖发表于:http://www.cnblogs.com/java123vip/p/9010373.html