Java中使用null的构造方法重载 [英] Constructor overloading using null in Java

查看:63
本文介绍了Java中使用null的构造方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是与Java中的构造函数重载相关的简单代码.让我们来看看吧.

Following is the simple code relevant to constructor overloading in Java. Let''s have a look at it.

package temp;

final public class Main
{
    private Main(Object o)
    {
        System.out.println("Object");
    }

    private Main(double[] da)
    {
        System.out.println("double array");
    }

    public static void main(String[] args)throws Exception
    {
        Main main = new Main(null);
    }
}



在上面的代码中,构造函数正在重载,其中一个构造函数的形式参数为Object,而另一个构造函数的形式参数为double[](数组).


Main main = new Main(null);

上面的语句正在调用构造函数之一,该语句使用null值作为其实际参数,并且程序在控制台上显示输出 double array .在这种情况下,编译器如何在运行时动态地解析特定的构造函数(或方法,如果是这样的话)?



In the above code, constructors are being overloaded in which one has a formal parameter of type Object and the other has the formal parameter of type double[] (array).


Main main = new Main(null);

One of the constructors is being invoked by the above statement which is using a null value as it''s actual argument and the program is displaying the output double array on the console. How does the compiler resolve a specific constructor (or a method, if such is a case) dynamically at run time in such a situation?

推荐答案

我认为答案可以可以在此处找到/java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#20448"target =" _ blank"title ="新窗口> ^ ],但您可能需要阅读通过它几次. (当您需要他时,他在哪里?).
I think the answer can be found here[^], but you may need to read through it a few times. (Where''s Torsten when you need him?).


您不能仅出于一个简单的原因就使用构造函数调用Main(null):歧义.所有三个构造函数的所有三个签名都与此调用匹配,因为Objectdouble[]String[]引用类型,因此任何参数都可以是null.

为了提供所需的语义而没有歧义,不可避免的是您应该再添加一个带有区域签名的构造函数.如果可以是没有参数的构造函数,则可以是具有一个原始类型参数的构造函数(例如Boolean,出于某种目的),可以是具有两个任意类型的参数的构造函数,等等.

很简单,不是吗?

—SA
You cannot use the constructor call Main(null) by only one simple reason: ambiguity. All three signatures of all three constructors match this call, as Object, double[] and String[] are reference types, so any of the parameters can be null.

To provide required semantic without ambiguity, it is unavoidable that you should add yet another constructor with district signature. If could be a constructor without parameters, a constructor with one primitive-type parameter (like Boolean, for whatever purpose), a constructor with two parameters of any type, etc.

Easy enough, isn''t it?

—SA


这篇关于Java中使用null的构造方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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