Passing null to the method preferring String, not

2019-04-06 00:24发布

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 .

3条回答
ら.Afraid
2楼-- · 2019-04-06 00:30

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.

查看更多
【Aperson】
3楼-- · 2019-04-06 00:41

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

查看更多
虎瘦雄心在
4楼-- · 2019-04-06 00:46

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);
查看更多
登录 后发表回答