Why doesn't ambiguity occur for parameter method ArithmeticException
Below code is executed without any ambiguity compilation error and the output is " ArithmeticException ". Guys can help me find out the reason.
class Test {
public static void main(String[] args) throws UnknownHostException, IOException {
testMetod(null);
}
// Overloaded method of parameter type Object
private static void testMetod(Object object) {
System.out.println("Object");
}
// Overloaded method of parameter type Exception
private static void testMetod(Exception e) {
System.out.println("Exception");
}
// Overloaded method of parameter type ArithmeticException
private static void testMetod(ArithmeticException ae) {
System.out.println("ArithmeticException");
}
}
source to share
In such cases, the rule follows the most specific method . Since ArithmeticException extends Exception
and ArithmeticException extends Object
, there is no ambiguity: ArithmeticException
more specific than any other.
If you add this:
private static void testMetod(String string) {
System.out.println("String");
}
You will get a compilation error because it is neither ArithmeticException extends String
true nor vice versa: there is no special parameter class.
It's probably important to say at this point that all of this happens at compile time. After eliminating the target method and compiling the code, calling the overloaded method is the same as calling any other method. This is different from the override method .
source to share