[英]How to create a Class with multiple constructors that use the same parameter type
我想做這樣的事情:
public class Arquivo { private File diretorio = null ; public Arquivo(File dir){ this.diretorio = dir; } public Arquivo(String dir){ this( new File(dir) ); } public Arquivo(String fileName){ this( new File("./src/Data/"+fileName) ); } }
您不能創建兩個接收單個String
參數的構造函數,只能存在一個這樣的構造函數。 簽名之間必須存在差異,例如,向其中一個構造函數添加第二個參數。
或者,您可以創建單個構造函數並在第二個參數中指示它是文件還是目錄:
// isFile == true means it's a file. isFile == false means it's a directory
public Arquivo(String fileName, boolean isFile) {
this(new File((isFile ? "./src/Data" : "") + fileName));
}
構造函數不能這樣做
一個懶惰的解決方案
public Arquivo(String s) {}
public Arquivo(String s, boolean b) {}
並且不要使用布爾值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.