gpt4 book ai didi

Scala 重载构造函数和 super

转载 作者:行者123 更新时间:2023-12-04 23:56:30 26 4
gpt4 key购买 nike

我无法理解如何在 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。请帮助。

附言我正在尝试创建自己的 BaseWebPage 派生自 wicket WebPage,这是 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 重载构造函数和 super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15623059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com