Multiple overloaded methods: Does null equal NullP

2019-01-17 14:55发布

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

2条回答
闹够了就滚
2楼-- · 2019-01-17 15:41

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-17 15:47

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.

[...]

查看更多
登录 后发表回答