如何为不同类型的可变数量的参数编写Java构造函数?

Kon*_*pov 5 java constructor

我必须为类Stamp写一个构造函数.构造函数最多需要五个 String,int和double类型的参数.所以,构造函数看起来像这样:

public Stamp(String code, int year, String country, double value, int numberOfCopies){...}
Run Code Online (Sandbox Code Playgroud)

问题是,由于正在创建Stamp类的对象,因此不能提供所有参数,即,可以将对象声明为

Stamp stamp = new Stamp("some_code", 1991, "Burkina Faso", 50, 1000);
Run Code Online (Sandbox Code Playgroud)

以及

Stamp stamp = new Stamp("some_code", 1991, "Burkina Faso");
Run Code Online (Sandbox Code Playgroud)

并且构造函数必须在两种情况下都工作,即使参数列表被截断(在后一种情况下,一些默认值被赋值给valuenumberOfCopies).当然,我可以编写六个构造函数(对于可能的参数数量,从0到5,假设参数始终遵循上述顺序,而不会混淆),但应该有更聪明的方法.我知道我可以声明构造函数

public Stamp(Object[] params){...}
Run Code Online (Sandbox Code Playgroud)

然后将params元素转换为相应的类.这可能会有效,但我总是要检查使用"if"条件为构造函数提供了多少参数,以便决定是否在未提供相应参数的情况下为变量分配默认值,或者使用提供的值(如果是给出.这一切看起来都很难看.因此,问题很简单:如果提供的参数列表长度不同且参数类型不同,构建构造函数(或其他方法)的方法是什么?

Ian*_*rts 9

这可能适用于建造者模式

public class Stamp {

  public static class Builder {
    // default values
    private String code = "default code"
    private int year = 1900;
    // etc.

    public Builder withCode(String code) {
      this.code = code;
      return this;
    }
    public Builder withYear(int year) {
      this.year = year;
      return this;
    }
    // etc.

    public Stamp build() {
      return new Stamp(code, year, country, value, numberOfCopies);
    }
  }

  public Stamp(String code, int year, String country, double value,
      int numberOfCopies){...}
}
Run Code Online (Sandbox Code Playgroud)

然后,施工过程变为

Stamp s = new Stamp.Builder()
                .withCode("some_code")
                .withYear(1991)
              .build();
Run Code Online (Sandbox Code Playgroud)

这样,参数不再依赖于顺序 - 您可以等效地说

Stamp s = new Stamp.Builder()
                .withYear(1991)
                .withCode("some_code")
              .build();
Run Code Online (Sandbox Code Playgroud)


Sur*_*tta 5

而不是搞乱Object[] 构造函数重用.

提供所有可能的构造函数并在内部使用它们

只是一个前任;

public Stamp(String code, int year)
{
    this(code, "", year,0,0); //calling your main constructor with missed values.
}
Run Code Online (Sandbox Code Playgroud)

到目前为止还没有其他工作.