Scala重载了构造函数和超级

前端之家收集整理的这篇文章主要介绍了Scala重载了构造函数和超级前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法理解如何在 Java上开发类似于以下内容的Scala代码

public abstract class A {
   protected A() { ... }
   protected A(int a) { ... }
}

public abstract class B {
   protected B() { super(); }
   protected B(int a) { super(a); }
}

public class C extends B {
   public C() { super(3); }
}

虽然很清楚如何开发C类,但我无法获得如何接受B.帮助.

附:我正在尝试创建自己的基于wicket WebPage的BaseWebPage,这是Java的常见做法

解决方法

你的意思是:

abstract class A protected (val slot: Int) {
    protected def this() = this(0)
}

abstract class B protected (value: Int) extends A(value) {
    protected def this() = this(0)
}

class C extends B(3) {
}

有一种AFAIK,无法绕过其中一种辅助形式的主要构造函数,即以下方法不起作用:

abstract class B protected (value: Int) extends A(value) {
    protected def this() = super()
}

所有辅助构造函数表单必须调用主要表单.从language specification(5.3.1构造函数定义):

A class may have additional constructors besides the primary constructor. These
are defined by constructor definitions of the form def this(ps1)…(psn) = e.
Such a definition introduces an additional constructor for the enclosing class,with
parameters as given in the formal parameter lists ps1,…,psn,and whose evaluation
is defined by the constructor expression e. The scope of each formal parameter is
the subsequent parameter sections and the constructor expression e. A constructor
expression is either a self constructor invocation this(args1)…(argsn) or a block
which begins with a self constructor invocation

(强调我的).

猜你在找的Scala相关文章