Null作為參數的時候,Java編譯器如何調用函數?

來源:互聯網
上載者:User

標籤:cal   ges   alt   先來   分享   如何   sub   ring   通過   

 1 public class TestNull { 2     public void method(Object o){ 3         System.out.println("Object Version"); 4     } 5      6     public void method(String s){ 7         System.out.println("String Version"); 8     } 9     10     public static void main(String[] args) {11         TestNull tn= new TestNull();12         tn.method(null);13     }14 15 }

   編譯可以通過,運行結果如下:

  那麼,Null作為參數的時候究竟如何調用函數?回答這個問題之前,先來看看其他例子。

public class TestCallMethod2 {    void test(Object s){ System.out.println("Object version");}    void test(TestCallMethod2 t){System.out.println("TestCallMethod2 version");}    void test(SubTestCallMthod2 t){System.out.println("SubTestCallMethod version");}    //void test(String s){System.out.println("String version");}        public static void main(String[] args) {        TestCallMethod2 t = new TestCallMethod2();        t.test(null);        t.test(new Object());    }}class SubTestCallMthod2 extends TestCallMethod2{}

  通過上述代碼可以知道,4個test()函數,當null作為實參進行調用的時候,會根據繼承的關係,調用最底層子類的test()函數,當第四個test()方法不注釋的時候,由於String類型和TestCallMethod2兩個類同屬於Object子類,同時存在兄弟類的test()方法,則會出現編譯錯誤。

 

Null作為參數的時候,Java編譯器如何調用函數?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.