java中多态性的实现
什么是多态
下面是多态存在的三个必要条件,要求大家做梦时都能背出来!
多态存在的三个必要条件
一、要有继承;
二、要有重写;
三、父类引用指向子类对象。
多态的好处:
1.可替换性(substitutability)。多态对已存在代码具有可替换性。例如,多态对圆circle类工作,对其他任何圆形几何体,如圆环,也同样工作。
2.可扩充性(extensibility)。多态对代码具有可扩充性。增加新的子类不影响已存在类的多态性、继承性,以及其他特性的运行和操作。实际上新加子类更容易获得多态功能。例如,在实现了圆锥、半圆锥以及半球体的多态基础上,很容易增添球体类的多态性。
3.接口性(interface-ability)。多态是超类通过方法签名,向子类提供了一个共同接口,由子类来完善或者覆盖它而实现的。如图8.3 所示。图中超类shape规定了两个实现多态的接口方法,computearea()以及computevolume()。子类,如circle和sphere为了实现多态,完善或者覆盖这两个接口方法。
4.灵活性(flexibility)。它在应用中体现了灵活多样的操作,提高了使用效率。
5.简化性(simplicity)。多态简化对应用软件的代码编写和修改过程,尤其在处理大量对象的运算和操作时,这个特点尤为突出和重要。
java中多态的实现方式:接口实现,继承父类进行方法重写,同一个类中进行方法重载。
一个小题目:
(一)相关类
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 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
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
如对本文有疑问, 点击进行留言回复!!
Caused by: java.lang.ClassNotFoundException: org.junit.platform.launcher.TestExecutionListener
网友评论