This question already has an answer here:
public class TestMain {
public static void methodTest(Exception e) {
System.out.println("Exception method called");
}
public static void methodTest(Object e) {
System.out.println("Object method called");
}
public static void methodTest(NullPointerException e) {
System.out.println("NullPointerException method called");
}
public static void main(String args[]) {
methodTest(null);
}
}
Output: NullPointerException method called
If there are several overloaded methods that might be called with a given parameter (
null
in your case) the compiler chooses the most specific one.See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5
In your case
methodTest(Exception e)
is more specific thanmethodTest(Object e)
, since Exception is a subclass of Object. AndmethodTest(NullPointerException e)
is even more specific.If you replace NullPointerException with another subclass of Exception, the compiler will choose that one.
On the other hand, if you make an additional method like
testMethod(IllegalArgumentException e)
the compiler will throw an error, since it doesn't know which one to choose.The compiler will try to match with the most specific parameter, which in this case is
NullPointerException
. You can see more info in the Java Language Specification, section 15.12.2.5. Choosing the Most Specific Method :