java - 如何让两个构造函数具有相同数量的参数但在java中用于不同的变量

标签 java constructor

<分区>

在我的例子中,该类将有两个构造函数,它们都将 3 个字符串作为参数,但是要在其中一个构造函数中初始化的字符串变量之一可能不同。 是否可以实现以下内容:

class A {
   String x = null;
   String y = null;
   String z = null;
   String a = null;

   A(String x, String y, String z) {
      ....
   }

   A(String a, String y, String z) {
      ....
   }
}

最佳答案

不,但是一个快速的解决方案是使用静态助手:

class A {

  String x, y, z, a;

  /** Constructor. Protected. See static helpers for object creation */
  protected A(String x, String y, String z, String a) {
    this.x = x;
    this.y = y;
    this.z = z;
    this.a = a;
  }

  /** Construct a new A with an x, y, and z */
  public static A fromXYZ(String x, String y, String z) {
    return new A(x, y, z, null);
  }

  /** Construct a new A with an a, y, and z */
  public static A fromAYZ(String a, String y, String z) {
    return new A(a, null, y, z);
  }
}

关于java - 如何让两个构造函数具有相同数量的参数但在java中用于不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17157737/

相关文章:

java - Android:显示文本的问题

c++ - 类成员初始化C++

java - 分配的最终对象字段在构造函数中可能仍然为 null 是真的吗?

java - 连接/链接 JTable UI

Java Error 参数错误,但它们是正确的?

java - 如何从 axis1 stub 获取传输的响应 header

java - 使用 Stream.sum() 多次消费流

c++ - 构造函数上没有匹配的函数调用

javascript - 如何为 Javascript 客户端使用构造函数

c++ - 带有initializer_list和size的std::unordered_map构造函数在main中编译,但不在类定义中编译