Error message "ambiguous for type" Other "when calling an overloaded method
I know the following program will have a compilation error like:
RunThis (Integer) method is ambiguous for type Other
I do not understand why.
public class Other {
public static void main(String[] args) {
runThis(null);
}
private static void runThis(Integer integer){
System.out.println("Integer");
}
private static void runThis(Object object){
System.out.println("Object");
}
private static void runThis(ArithmeticException ae){
System.out.println("ArithmeticException");
}
}
Also, when I change the program as follows, it prints "ArithmeticException". And I don't know the reason. Can someone explain this to me?
public class Other {
public static void main(String[] args) {
runThis(null);
}
private static void runThis(Exception exception){
System.out.println("Exception");
}
private static void runThis(Object object){
System.out.println("Object");
}
private static void runThis(ArithmeticException ae){
System.out.println("ArithmeticException");
}
source to share
On transition to null
, which can be converted to any reference type. Java will try to find the overloaded method with the most specific type.
In your first example, the possibilities Object
, Integer
and ArithmeticException
. Integer
and ArithmeticException
are more specific than Object
, but not more specific than others, so they are ambiguous.
In your second example, the possibilities Object
, Exception
and ArithmeticException
. Exception
and ArithmeticException
are more specific than Object
, but ArithmeticException
also more specific than Exception
, so ambiguity is allowed in favor ArithmeticException
.
source to share