码迷,mamicode.com
首页 > 编程语言 > 详细

Null作为参数的时候,Java编译器如何调用函数?

时间:2017-03-17 23:25:08      阅读:212      评论:0      收藏:0      [点我收藏+]

标签: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编译器如何调用函数?

标签:cal   ges   alt   先来   分享   如何   sub   ring   通过   

原文地址:http://www.cnblogs.com/holybell/p/6568939.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!