如何让两个构造函数具有相同数量的参数,但是对于java中的不同变量

fmj*_*ar3 4 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) {
      ....
   }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 13

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)


A.H*_*.H. 9

是否可以实现以下内容

没有.

因为编译器没有内置的水晶球,以便在编译时选择合适的构造函数.

请注意两点:

  • 编译后,构造函数签名中的参数名称将丢失 - 它们是纯人类糖.所以它们不能用于在两个ctors之间发送.

  • 参数名称与字段名称无关.两者通常是相同的,编译器无关紧要.


fge*_*fge 9

你不能这样做.您不能拥有两个具有完全相同签名的构造函数,也不能拥有两个具有完全相同签名的方法.参数名称无关紧要.

一种解决方案是使用所谓的静态工厂方法:

// in class A
// Parameter names could be "tar", "feathers" and "rope" for what it matters
public static A withXYZ(String x, String y, String z)
{
    final A ret = new A();
    ret.x = x; ret.y = y; ret.z = z;
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

在代码中:

final A myA = A.withXYZ(whatever, you, want);
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用构建器.

有关现成的解决方案,请参阅下面的@ Andy的答案.