How to create a Class with multiple constructors that use the same parameter type

我只是一个虾纸丫 提交于 2019-12-21 18:40:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!