无参数构造函数将抛出错误,因为编译器不知道要调用哪个构造函数。解决方案是什么?
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 {
}
答案 0 :(得分:5)
Typecast null
:
private Test() throws Exception {
this((String)null); // Or of course, this((InputStream)null);
}
但是你想用Test(String)
参数来呼叫Test(InputStream)
或null
似乎有点奇怪......
答案 1 :(得分: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));
}