5

在我的情况下,该类将有两个构造函数,它们都将 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) {
      ....
   }
}
4

5 回答 5

15

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

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);
  }
}
于 2013-06-17T22:17:33.787 回答
9

是否可以实现以下

不。

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

请注意两点:

  • 构造函数签名中的参数名称在编译后会丢失——它们是纯人类的糖。因此它们不能用于在两个 ctor 之间进行调度。

  • 参数名称与字段名称无关。两者通常相同是编译器不关心的。

于 2013-06-17T22:13:29.357 回答
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;
}

在代码中:

final A myA = A.withXYZ(whatever, you, want);

另一种解决方案是使用builder

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

于 2013-06-17T22:14:53.887 回答
2

简而言之:没有。

长答案:它们有什么不同?如果它们非常不同,您可能需要考虑创建一个基类并对其进行扩展。

另一种选择是创建一个 StringType 枚举并将其与构造函数一起传递。

通常,如果您有两个相似的构造函数,则需要审查您的设计。

于 2013-06-17T22:14:14.960 回答
0

当然不。如果我写:

A a = new A("foo", "bar", " ");

那么我会调用哪个构造函数?

您的选择是使用静态方法,即:

public static A withXYZ(String x, String y, String z) 
{
    final A a = new A();
    a.x = x;
    a.y = y;
    a.z = z;
    return a;
}

A myA = A.withXYZ("foo", "bar", " ");

否则,您可以在构造后使用普通设置器注入值,即:

A a = new A();
a.setX("foo");
a.setY("bar");
a.setZ(" ");
于 2013-06-17T22:30:24.587 回答