2012-04-25 18 views
2

引数のないコンストラクタは、どのコンストラクタを呼び出すべきかをコンパイラが知らないため、エラーをスローします。解決策は何ですか?null引数を持つオーバーロードされたコンストラクタを呼び出す

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

答えて

5

型キャストnull

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

しかし、それはあなたがnull引数でTest(String)Test(InputStream)を呼び出したいだろうと少し奇妙に思える...

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)); 
} 
関連する問題