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的构造函数具有什么样的行为?