Java - 如何根据继承类的构造函数参数调用不同的super()?

Oro*_*ron 5 java inheritance super

我试图让继承类要求更少的参数,并计算超类的'正确'mising参数.寻求有关如何执行此操作的帮助,而不使用工厂方法.

这是简化操作的示例代码.Son(int)将根据int的值调用super(int,boolean).

class Base {
  ...
  public Base (int num, boolean boo2) { ...}
  ...
}

class Son extends Base {
  ...
  public Son (int num) {
    if (num > 17)
       super(num, true);
    else
      super(num , false);
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

我还考虑过将Base作为接口,但这不允许我强制执行一些参数正确性检查.

感谢您的帮助.

Osc*_*rez 6

我不是百分百肯定,但这可以吗?

class Son extends Base {
  ...
  public Son (int num) {
       super(num, (num>17));
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*gio 3

如果查找其他参数是一个复杂的操作(即不能简化为单个表达式),您可以添加一个静态方法来为您执行此操作并在超级调用中引用它,例如:

Class Son extends Base {

  private static boolean getMyBoolean(int num) {
    return num > 17; //or any complex algorithm you need.
  }

  public Son (int num) {
    super(num, getMyBoolean(num));
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

否则,如果可以使用简单的表达式计算缺失的参数(如您给出的具体示例所示),只需编写:

Class Son extends Base {
  public Son (int num) {
    super(num, num > 17);
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)