Object vs. String Method

Possible duplicate:
Overloaded selection method based on real type parameters
How is an overloaded method selected when a parameter is a literal value?

When executing the code below, I get the following output:

Method with argument String 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); } } 
+6
source share
5 answers

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); } } 

Printed Test 3

As in your scenario, this means that if the method is overloaded (and when null is passed), it will recognize the method with the largest parameter for the child.

 Object->Test->Test2 

or in your case:

 Object->String 
+1
source

null in the call matches the signals of test (). You must specify null for it to call one or the other.

+3
source

A similar example from Java Puzzles, if I remember correctly.

null can be of type String or Object . But the JVM will always choose a more accurate method .

In this case, String more accurate and then Object . (a String is an Object , but an Object may not be a String ).

It’s not so good to write such code. Try to specify the parameters according to your desired method, for example

 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); } } 
+2
source

Java is trying to find the most suitable method that can be called. String is a subclass of the object, so Java defers to the String method whenever possible. null is a perfectly acceptable value for Object or String, but since String is more specific than Object, Java abandons the String method because it is more accurate.

+1
source

null can be either String or / or Object , but since String inherits from Object , it will try to use a more precise signature. You can use null to choose a method:

 public static void main(String[] args) { Test.test((Object) null); // treats as Object Test.test((String) null); // treats as String Test.test(null); // treats as String } 
0
source

All Articles