av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁技術文章
文章詳情頁

淺談Java方法調用的優先級問題

瀏覽:4日期:2022-08-23 13:13:34

實現Java多態性的時候,關于方法調用的優先級:

我們這樣假設下,super(超類)、this(當前類對象)、show(方法)、object(對象),方法調用優先順序: ①this.show(object)>②super.show(object)> ③this.show((super)object)>④super.show((super)object)

先看以下代碼

class ParentCls {public String show(ChildA obj){return 'Parent and ChildA';}public String show(ParentCls obj) {return 'Parent';}}

然后寫一個子類ChildA ,繼承ParentCls :

class ChildA extends ParentCls{public String show(ChildA obj) {return 'ChildA';};public String show(ParentCls obj) {return 'ChildA and Parent';};}

寫一個子類ChildB,繼承ChildA :

class ChildB extends ChildA{

}

測試下

public static void main(String[] args) {ParentCls p1 = new ParentCls();ParentCls p2 = new ChildA();ChildA a = new ChildA();ChildB b = new ChildB();System.out.println(p1.show(a));System.out.println(b.show(a));System.out.println(a.show(b));System.out.println(p2.show(a));}

輸出

Parent and ChildAChildAChildAChildA

第一個輸出,p1是ParentCls的實例,且類ParentCls中有show(ChildA obj)方法,直接執行該方法, ①有效;

第二個輸出,b是ChildB 的實例,類ChildB 中沒有show(ChildA obj)方法,①無效,再從ChildB 的父類ChildA查找,ChildA中剛好有show(ChildA obj)方法,②有效;

第三個輸出,a是ChildA的實例,b是ChildB的實例,類ChildA中沒有show(ChildB obj)方法,①無效,再從ChildA的父類ParentCls入手,ParentCls中也沒有show(ChildB obj)方法,②無效,從ChildB的父類入手,(super)ChildB 即是ChildA,所以a.show(b)=>a.show(a),ChildA中剛好有show(ChildA obj)方法,③有效;

④就不作演示,根據①②③很容易得出結論;

第四個輸出,體現Java多態性,符合①,但是p2是引用類ChildA的一個對象 ,ChildA 重寫覆蓋了ParentCls的show()方法,所以執行ChildA 的show()方法;

補充知識:Java中關于靜態塊,初始化快,構造函數的執行順序

代碼如下:

public class ParentDemo { static { System.out.println('this is ParentDemo static'); } { System.out.println('this is ParentDemo code block'); } public ParentDemo() { System.out.println('this is ParentDemo constructor'); }}public class SonDemo extends ParentDemo{ static { System.out.println('this is SonDemo static'); } { System.out.println('this is SonDemo code block'); } public SonDemo() { System.out.println('this is SonDemo constructor'); }}public class TestMain { public static void main(String[] args){ new SonDemo(); }}

輸出結果:

this is ParentDemo staticthis is SonDemo staticthis is ParentDemo code blockthis is ParentDemo constructorthis is SonDemo code blockthis is SonDemo constructor

由上可見,Java中 靜態塊中的代碼在類加載時執行,子類繼承父類。會按照繼承的順序先執行靜態代碼塊。當實例化對象的時候,同理會按照繼承的順序依次執行如下代碼:

代碼塊,構造函數,當父類的執行完以后,再執行子類。

以上這篇淺談Java方法調用的優先級問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 国产午夜视频 | 亚洲精品99 | 中文字幕亚洲精品 | 精品视频一区二区三区 | 尤物视频在线免费观看 | 精品亚洲国产成av人片传媒 | 精品欧美一区二区在线观看欧美熟 | 精品视频久久久久久 | 亚洲精品成人 | 久久久亚洲 | 国产日韩一区二区三区 | 伊人国产精品 | 天天天天天天天干 | 亚洲91视频 | 免费啪啪| 亚洲91 | 四虎影音 | 久久成人18免费网站 | 别c我啊嗯国产av一毛片 | 国产美女自拍视频 | 99精品视频免费观看 | 亚洲一区二区在线 | 精品国产91 | 中文字幕欧美日韩一区 | 日本91av视频 | 欧美精品日韩精品 | 国产色婷婷精品综合在线播放 | 毛片视频网站 | 天天综合网永久 | 成人免费小视频 | 欧美日韩国产在线观看 | 国产成人av在线播放 | 精品无码久久久久久久动漫 | 日韩欧美不卡 | 国产色网 | 日韩欧美在线视频一区 | 国产成人免费在线 | 久久婷婷国产麻豆91 | 精品三区| 久久久69 | 日本黄色大片免费 |