Calling overloaded functions with “null” reference

2019-02-26 08:25发布

问题:

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);