2012-04-25 40 views
2

由於編譯器不知道要調用哪個構造函數,因此no參數構造函數將引發錯誤。解決辦法是什麼?調用帶有空參數的重載構造函數

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

你正在嘗試做不起作用,因爲它並沒有真正意義。你期望什麼樣的行爲,使用null作爲參數的構造函數具有? – posdef 2012-04-25 09:06:58

回答

5

類型轉換null

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

但似乎有點奇怪,你會想打電話Test(String)Test(InputStream)null參數...

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)); 
}