Possible Duplicate:
Method Overloading for NULL parameter
In the code below the output is
String
and if I remove the method with the parameter of type String then the output is
Object
I know how overloading of methods acts when the parameter types don’t match exactly but I can not understand how null can be treated as an Object and/or a String parameter.
What is the explanation for this?
class C {
static void m1(Object x) {
System.out.print("Object");
}
static void m1(String x) {
System.out.print("String");
}
public static void main(String[] args) {
m1(null);
}
}
It always uses the most specific method according to the Java specs, section 15.12.2.5.
The intro is reasonably specific about it:
Generally speaking, and at least for code readability, it’s always best to try to be as explicit as possible. You could cast your
nullinto the type that matches the signature you want to call. But that’s definitely a questionable practice. It assumes everyone knows this rule and makes the code more difficult to read.But it’s a good academic question, so I +1 your question.