在具有重载构造函数的类中传递null时首先调用哪个构造函数? [英] Which constructor is called first while passing null in the class having overloaded constructor?

查看:246
本文介绍了在具有重载构造函数的类中传递null时首先调用哪个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是具有3个重载构造函数的java类:

Below is the java class having 3 overloaded constructors :

public class Test {

    public Test(Object i){
        System.out.println("Object invoked");
    }

    public Test(String i){
        System.out.println("String invoked");
    }

    public Test(int k){
        System.out.println("Integer invoked");
    }

    public static void main(String[] args) throws Exception {

        Test t = new Test(null);
    }
}

如果在创建新实例时传递空值class,将调用哪个构造函数?是什么原因?

If null value is passed while creating the new instance of class, which constructor will be invoked ? What is the reason ?

推荐答案

Java总是选择最符合特定的方法(或构造函数)适用于你通过的论点。在这种情况下,那是 String 构造函数 - String Object的子类

Java always chooses the most specific method (or constructor) that would be applicable for the argument you pass. In this case, that's the String constructor -- String is a subclass of Object.

想想如果你有什么会发生什么

Think about what would happen if you had

new Test("some string")

Both Object String 构造函数将适用于此处。毕竟,参数既是对象又是 String 然而,很明显将调用 String 构造函数,因为它比 Object 构造函数仍然适用于给定参数。

Both the Object and String constructors would be applicable here. After all, the argument is both an Object and a String. However, it is clear that the String constructor will be invoked because it is more specific than the Object constructor and still is applicable given the argument.

null 没有区别;这两个构造函数仍然适用,并且 String 构造函数仍然在 Object 构造函数中被选中,原因相同。

null is no different; these two constructors are still applicable, and the String constructor is still chosen over the Object one for the same reason.

现在,如果存在两个同样特定的构造函数(例如,如果你有一个 Integer 构造函数)那么当你调用测试(null)时出现编译错误。

Now, if there were two equally "specific" constructors present (e.g. if you had an Integer constructor) there would be a compilation error when you call Test(null).

这在JLS§15.12.2


第二步搜索上一步中为成员方法确定的类型。此步骤使用方法的名称和参数表达式的类型来定位可访问和适用的方法,即可以在给定参数上正确调用的声明。

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

可能有多个这样的方法,在这种情况下,选择最具体的方法。最具体方法的描述符(签名加返回类型)是在运行时用于执行方法调度的方法。

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

显式JLS§15.12.2.5

这篇关于在具有重载构造函数的类中传递null时首先调用哪个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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