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

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

+4
source share
3 answers

You cannot with a constructor, which is one of the limitations of constructors

time to start using static factory template


see also

+10
source

, String, . , , .

, :

// isFile == true means it a file. isFile == false means it a directory
public Arquivo(String fileName, boolean isFile) {
    this(new File((isFile ? "./src/Data" : "") + fileName));
}
+3

The designer cannot do this

lazy decision will be

public Arquivo(String s) {}

public Arquivo(String s, boolean b) {}

and just don't use boolean

-1
source

All Articles