简体   繁体   English

如何使用具有相同参数类型的多个构造函数创建类

[英]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. 您不能创建两个接收单个String参数的构造函数,只能存在一个这样的构造函数。 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 并且不要使用布尔值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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