Calling overloaded functions with “null” reference

丶灬走出姿态 提交于 2019-12-31 03:32:30

问题


Let us say I have following overloaded functions

public class Test {

    public static void funOne(String s){
        System.out.print("String function");
    }

    public static void funOne(Object o){
        System.out.print("Object function");
    }

    public static void main(String[] args) {            
        funOne(null);
    }
}

Why would funOne(null) call the method with String argument signature? what is the precedence for overloading here?


回答1:


The class that is lower in the class hierarchy will have precedence in this case. In other words the more specific class type, which would be String in this case because String extends Object technically.

If you have the following

public class A {
    ...
}

public class B extends A {
    ...
}

Then when you define overloading methods like the following:

public void test(A object) {
    ...
}

public void test(B object) {
    ...
}

Then calling test(null) will call the second method because B is lower in the class hierarchy.




回答2:


Your question is more fully answered here with references.

Also, you can force a particular method to be called by doing this:

    funOne((Object) null);


来源:https://stackoverflow.com/questions/22887775/calling-overloaded-functions-with-null-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!