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