Reputation: 567
I have no idea how to ask this question or what title to use. I hope i do not violate any rules. Anyway, can someone explain to me the following behavior? 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 get is this:
X:Double
Why it ignores completely the line
void dosmth(Object obj) { System.out.println("X:Object"); }
And why null corresponds to Double and not Object?
In addition, if i add this line:
void dosmth(Integer obj) {System.out.println("X:Integer"); }
i get the following error:
both method dosmth(java.lang.Integer) and method dosmth(java.lang.Double) match
Upvotes: 3
Views: 113
Reputation: 393791
When choosing an overloaded method, null
can correspond to any reference type. When there are two candidates - Object
and Double
in your case - the most specific one is chosen - Double
(Double
is more specific than Object
since it's a sub-class of Object
).
When you introduce void dosmth(Integer obj)
, there are three candidates - Object
, Double
and Integer
- but since neither Double
nor Integer
is more specific than the other - the compiler can't choose between then and you get an error.
As mentioned by FINDarkside, if you which a specific method to be chosen, you can cast the null
to the desired type.
For example, this will force the compiler to choose void dosmth(Object obj)
:
x.dosmth((Object)null);
Upvotes: 12
Reputation: 195
Double
is more specific than Object
. From the specification:
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
Upvotes: 1