Possible Duplicate:
Overloaded method selection based on the parameter’s real type
How is an overloaded method choosen when a parameter is the literal null value?
When I execute the code below, I get the following output:
Method with String argument Called ..."
Why?
public class StringObjectPOC {
public static void test(Object o) {
System.out.println("Method with Object argument Called ...");
}
public static void test(String str){
System.out.println("Method with String argument Called ...");
}
public static void main(String[] args) {
StringObjectPOC.test(null);
}
}
The null
in the call matches both the test() signatures. You have to cast the null
to ensure it calls one or the other.
A similar example is from Java Puzzles if I recall correctly.
null
can be of String
type or Object
type. But the JVM will always choose a more accurate method.
In this case, String
is more accurate then Object
. (a String
is an Object
, but an Object
might not be a String
).
It is not a good habit to write code like this. Try to cast parameters to match your desired method, like
public class StringObjectPOC {
public static void test(Object o) {
System.out.println("Method with Object argument Called ...");
}
public static void test(String str){
System.out.println("Method with String argument Called ...");
}
public static void main(String[] args) {
StringObjectPOC.test((Object)null);
}
}
I tried this:
Test2.class
public class Test2{}
Test3.class
public class Test3 extends Test2{
}
Test.class
public class Test{
public static void print(Object obj){
System.out.println("Object");
}
public static void print(Test2 obj){
System.out.println("test 2");
}
public static void print(Test3 obj){
System.out.println("Test 3");
}
public static void main(String[]args){
Test.print(null);
}
}
it printed out Test 3
Just like in your scenario, this means that if a method is overloaded (and when null is passed), it recognizes the method which has the child-most parameter.
Object->Test->Test2
or in your case:
Object->String
Java tries to find the most specific method possible to call. String is a subclass of object, so Java will defer to the String method whenever it can. null is a perfectly acceptable value for either an Object or a String, but since a String is more specific than an Object, Java defers to the String method because it is more precise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With