简体   繁体   中英

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

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

You can't with constructor, that is one of the limitation of constructors

time to start using static factory pattern


See Also

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM