国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java多態的理解

2019-11-06 08:13:40
字體:
來源:轉載
供稿:網友

下面的代碼相信很多人都看過,但是很多人并不知道具體的原理。。。所以把我的理解記錄下來,供大家參考。。 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類中沒有對應的方法,這時我們應該到A類的父類中去找這個方法,但是A類沒有父類,所以我們轉向括號內對象,因為B是繼承自A,可以將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))的順序來進行多態調用方法的排序
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 巫溪县| 湖口县| 青岛市| 荆门市| 大方县| 体育| 那曲县| 灵川县| 辽宁省| 忻城县| 三台县| 汾西县| 大名县| 和顺县| 奉新县| 建德市| 台东市| 辽中县| 阜新| 习水县| 河西区| 孟州市| 台安县| 宜章县| 黔南| 青阳县| 原平市| 正定县| 大城县| 轮台县| 巴南区| 黄浦区| 河间市| 綦江县| 马山县| 和平区| 华亭县| 榕江县| 新龙县| 永城市| 犍为县|