2

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

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 {

}
4

2 回答 2

5

类型转换null

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

但是你想要打电话Test(String)或争论似乎Test(InputStream)有点奇怪......null

于 2012-04-25T09:03:57.297 回答
1

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

我会这样做:

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));
}
于 2012-04-25T09:11:26.130 回答