Java null corresponds to double

I don't know how to raise the question or what title to use I hope I don't break any rules Anyway, can someone explain the following behavior to me? I have this Code:

X x = new X();
x.dosmth(null);

static class X{
        void dosmth(Object obj) { System.out.println("X:Object"); }
        void dosmth(Double obj) { System.out.println("X:Double"); }
        void dosmth(int obj) { System.out.println("X:int"); }
        void dosmth(double obj) { System.out.println("X:double"); }
        void dosmth(char obj) { System.out.println("X:char"); }
        void dosmth(byte obj) { System.out.println("X:byte"); }
}

What I got was this:

X:Double

Why does it completely ignore this line

void dosmth(Object obj) { System.out.println("X:Object"); }

Why does null correspond to double instead of object?

Also, if I add this line:

void dosmth(Integer obj) {System.out.println("X:Integer"); }

I received the following error:

both method dosmth(java.lang.Integer) and method dosmth(java.lang.Double) match

Solution

When you select an overloaded method, null can correspond to any reference type If there are two candidates - object and double in your case - select the most specific one - double (double is more specific than object because it is a subclass of object)

When you introduce void dosth (integer obj), there are three candidates - object, double and integer - but since neither double nor integer is more specific than the other - the compiler cannot choose between that and you will get an error

As mentioned in findarkside, if you select a specific method, you can convert null to the required type

For example, this forces the compiler to select void dosth (object obj):

x.dosmth((Object)null);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>