5

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

3 Answers 3

11

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

time to start using static factory pattern


See Also

Sign up to request clarification or add additional context in comments.

4 Comments

Also, consider how you would use such a pair of constructors. What do you expect new Arquivo("foo") would do? Which constructor would it call?
@ysha I could wrap the construction logic in conjunction with setters inside my factory method or I would use Builder pattern
Sorry, the "you" there was meant for the OP. :) I was getting at the fact that if Java did allow two constructors with the same signature, it would make usages of those constructors ambiguous. I +1'd your answer -- factory methods are the way to go here.
3

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

Comments

-1

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

3 Comments

is there a way to do something similar to this, however, using the the most resource-friendly path ?. the solution you provided may be more suitable for the occasion, otherwise, i would have to change some extra code in my project.
It can be really, really confusing to use a 'magic boolean'. Coders not expecting this may waste time hunting down a boolean in the code that doesn't exist, and may presume one was deleted (by accident? Who knows?) without documentation.
like you said without documentation, which is not right in its own. then i again i said a lazy solution, i agree with you however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.