I'm confused in below examples. some one can please explain me why in Example 1 it will print "st" and in Example 2 give compile time ambiguity for non primitive types and non parent-child relations classes.
Example 1
public class FinalTest {
public static void main(String[] args) {
name(null);
}
public static void name(String s) {
System.out.println("st");
}
public static void name(Object s) {
System.out.println("obj");
}
}
Example 2
public class FinalTest {
public static void main(String[] args) {
name(null);
}
public static void name(String s) {
System.out.println("st");
}
public static void name(Integer s) {
System.out.println("obj");
}
}
In Example 1 public static void name(String s)
is more specific than public static void name(Object s)
. So the null
in name(null);
is supposed to be a String
object being null
.
But in Example 2 both public static void name(String s)
and public static void name(Integer s)
are equal in specific. So both method name(String)
in FinalTest
and method name(Integer)
in FinalTest
match for name(null);
.
See 15.12.2.5. Choosing the Most Specific Method for a detailed description.
The following should work:
public class FinalTest {
public static void main(String[] args) {
String s = null;
name(s);
Object o = null;
name(o);
Integer i = null;
name(i);
}
public static void name(String s) {
System.out.println("String");
}
public static void name(Object s) {
System.out.println("Object");
}
public static void name(Integer s) {
System.out.println("Integer");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.