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

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

要正确理解多态,我们需要明确如下概念:

・定义类型和实际类型

・重载和重写

・编译和运行

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

重载发生在编译阶段,由定义类型决定。

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

确定a.fun(b)最终调用了哪个类的哪个方法,可以通过如下几步进行:

1.运用继承规则,确定每个类具有的全部方法,包括父类的方法;

2.运用重载规则,确定编译阶段对应的定义类型的方法;

3.运用重写规则,确定运行阶段对应的实际类型的方法;

注:重写规则如果找不到同名同参同参同参的方法,则调用父类同名同参同参同参的方法。与重载规则无关无关无关。

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

1 classA {2 publicString show(D obj)...{3 return ("A and D");4 }5 publicString show(A obj)...{6 return ("A and A");7 }8 }9 class B extendsA{10 publicString show(B obj)...{11 return ("B and B");12 }13 publicString show(A obj)...{14 return ("B and A");15 }16 }17 class C extendsB...{}18 class D extends B...{}

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

A a1 = newA();

A a2= newB();

B b= newB();

C c= newC();

D d= newD();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值