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
When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value.
Method overloading is possible only if the overloaded methods have different signatures. It cannot be possible if the signature is same and only the return type is different.
To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.
The Null Pointer Exception extends from the class RuntimeException. The hierarchy of NullPointerException is given below. As shown in the above hierarchy, Null Pointer Exception extends from the RuntimeException that inherits the Exception Class.
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 than methodTest(Object e)
, since Exception is a subclass of Object. And methodTest(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
:
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With