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。继承

相关文章
相关标签/搜索