多个重载方法:null是否等于NullPointerException? [英] Multiple overloaded methods: Does null equal NullPointerException?

查看:172
本文介绍了多个重载方法:null是否等于NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
    }   
}

输出:名为

推荐答案

如果有多个重载方法可能使用给定参数调用( null ) case)编译器选择最具体的一个。

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.

参见 http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

在你的情况下 methodTest(例外e)更具体> methodTest(Object e),因为Exception是Object的子类。并且 methodTest(NullPointerException e)更具体。

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.

如果用另一个Exception子类替换NullPointerException,编译器会选择那个。

If you replace NullPointerException with another subclass of Exception, the compiler will choose that one.

另一方面,如果你做了一个额外的方法,比如 testMethod(IllegalArgumentException e)编译器会抛出错误,因为它不知道选择哪一个。

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.

这篇关于多个重载方法:null是否等于NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆