问题
I am trying to do something like this:
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) );
}
}
回答1:
You can't with constructor, that is one of the limitation of constructors
time to start using static factory pattern
See Also
- What are static factory methods?
回答2:
You can't create two constructors that receive a single String parameter, there can only exist one such constructor. There must be a difference between the signatures, for example, add a second parameter to one of the constructors.
Alternatively, you could create a single constructor and indicate in a second parameter whether it's a file or a directory:
// 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));
}
回答3:
A constructor can not do that
a lazy solution would be
public Arquivo(String s) {}
public Arquivo(String s, boolean b) {}
and just don't use the boolean
来源:https://stackoverflow.com/questions/19643989/how-to-create-a-class-with-multiple-constructors-that-use-the-same-parameter-typ