在 child class 实例化中使用替代的超级 class 构造函数

Using alternative super class constructor in child class instantiation

我有一个基础 class 有两个构造函数,还有一个 child class 有一个构造函数。是否可以使用第二个基础 class 构造函数实例化 child class?

示例代码:

abstract class RuleCondition(rule:Rule, field:String, equal:Boolean, inverted:Boolean)
{
  // alternate constructor with RuleValue instead of static comparation value

  def this(rule:Rule, field:String, ref:RuleValue, equal:Boolean = false, inverted:Boolean = false) = ???
 }

class RuleConditionAbove(rule:Rule, field:String, comparationValue:Long, equal:Boolean = false, inverted:Boolean = false)
  extends RuleCondition(rule, field, equal, inverted)
{
    // ...
}

现在我可以做到了:

val myAboveCondition = new RuleConditionAbove(rule, "bla", 10, true, false)

但我不能这样做:

val myAboveCondition = new RuleConditionAbove(rule, "bla", RuleValue(...), true, false)

因为 RuleCondition 基础 class 的替代构造函数不可见。一旦我将其添加到 child class:

,它 可见
def this(rule:Rule, field:String, ref:RuleValue, equal:Boolean = false, inverted:Boolean = false) = this(rule, field, ref, equal, inverted)

这会是解决此问题的 only/usual 方法吗,还是有更智能的方法可以减少复制和过去的代码? (因为我有大量相同模式的 child classes)

[edit] 澄清一下,第二个构造函数 在每个 child class 中都是相同的,因此我只想实现它曾经在基地 class。 然而,仍然必须在每个 child class 中放置另一个构造函数会以某种方式破坏这个目的,因此我不会在基础 class 中有两个构造函数,而是只在所有 child classes.

Is it possible to instanciate a child class using the [second] base class constructor?

没有

您永远不能使用超级class 构造函数来创建子class 的实例。您必须为正在创建的 class 调用构造函数。 subclass的构造函数必须调用superclass的构造函数,但不能直接调用。

所以你可以这样做的原因

val myAboveCondition = new RuleConditionAbove(rule, "bla", 10, true, false)

RuleConditionAbove 有一个带有这些参数的构造函数。它与 RuleCondition 具有具有相同参数的构造函数这一事实无关。

以及你不能这样做的原因

val myAboveCondition = new RuleConditionAbove(rule, "bla", RuleValue(...), true, false)

RuleConditionAbove 没有带有这些参数的构造函数。

您必须按照您的描述在每个子 class 中添加一个构造函数定义。

def this(rule:Rule, field:String, ref:RuleValue, equal:Boolean = false, inverted:Boolean = false) = this(rule, field, ref, equal, inverted)

假设子 class 定义了基础 class 中不可用的新字段。使用基本构造函数创建子 class 不会定义此类字段,并使 class 的实例部分初始化。

如果您的基础构造函数具有有价值的逻辑,将其保留在基础中是有意义的 class。只是 "link" 它到子 class.

中的基本构造函数