Passing null to the method preferring String, not

2019-04-06 00:26发布

问题:

I am facing an issue in my program and I made it clear with a small code snippet below. Can anyone explain why this is happening?

class ObjectnullTest {

    public void printToOut(String string) {

        System.out.println("I am null string");
    }


    public void printToOut(Object object)

        System.out.println("I am  null object");
    }



class Test {

    public static void main(String args[]) {

        ObjectnullTest a = new ObjectnullTest();
        a.printToOut(null);

    }
}

This always prints I am null string .

I want to know the reason so that I can modify the code .

回答1:

It's because In case of method Overloading

The most specific method is choosen at compile time.

As 'java.lang.String' is a more specific type than 'java.lang.Object'. In your case the method which takes 'String' as a parameter is choosen.

Its clearly documented in JLS:

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run-time to perform the method dispatch.



回答2:

I agree with the existing comment about selection of the most specific method. You can force your null to be treated as an Object reference, eliminating use of the String argument method, by casting it:

a.printToOut((Object)null);


回答3:

please see section 15.12.2.5 of jls that give in detail how to choose

The most specific method is choosen at compile time