Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 510
Hydrocat Avatar asked Dec 16 '22 04:12

Hydrocat


2 Answers

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?
like image 108
jmj Avatar answered Apr 19 '23 23:04

jmj


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));
}
like image 44
Óscar López Avatar answered Apr 19 '23 23:04

Óscar López