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

 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做爲參數的時候究竟如何調用函數?回答這個問題以前,先來看看其餘例子。spa

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()方法,則會出現編譯錯誤。code

 

————————————————————————————————擴展——————————————————————————————————————————blog

public interface GrandFather {}
public interface Father extends GrandFather {}
public interface Son extends Father {}
public class TestInterface implements GrandFather,Father,Son{
    
    public void test(GrandFather g){System.out.println("GrandFather version");}
    public void test(Father f){System.out.println("Father version");}
    public void test(Son s){System.out.println("Son version");}
    
    public static void main(String[] args) {
        TestInterface ti = new TestInterface();
        ti.test(ti);
    }
}

  輸出:Son version。繼承

相關文章
相關標籤/搜索