Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用null参数调用重载构造函数_Java - Fatal编程技术网

Java 使用null参数调用重载构造函数

Java 使用null参数调用重载构造函数,java,Java,无参数构造函数将抛出错误,因为编译器不知道调用哪个构造函数。解决办法是什么 private Test() throws Exception { this(null);//THIS WILL THROW ERROR, I WAN'T TO CALL A SPECIFIC CONSTRUCTOR FROM THE TWO BELOW. HOW TO DO?? } private Test(InputStream stream) throws Exception { } private

无参数构造函数将抛出错误,因为编译器不知道调用哪个构造函数。解决办法是什么

private Test() throws Exception {
    this(null);//THIS WILL THROW ERROR, I WAN'T TO CALL A SPECIFIC CONSTRUCTOR FROM THE TWO BELOW. HOW TO DO??
}
private Test(InputStream stream) throws Exception {

}



private Test(String fileName) throws Exception {

}

键入
null

private Test() throws Exception {
    this((String)null); // Or of course, this((InputStream)null);
}

但是你想用一个
null
参数调用
Test(String)
Test(InputStream)
似乎有点奇怪…

我不明白为什么所有这些精心设计的构造函数都是私有的

我会这样做:

private Test() throws Exception {
    this(new PrintStream(System.in);
}

private Test(InputStream stream) throws Exception {
    if (stream == null) {
        throw new IllegalArgumentException("input stream cannot be null");
    }   
    // other stuff here.
}    

private Test(String fileName) throws Exception {
    this(new FileInputStream(fileName));
}

你想做的事情不起作用,因为它没有真正意义。您希望参数为null的构造函数具有什么样的行为?