抽象类中辅助构造函数的用例是什么?
考虑这段代码:
abstract class Foo(val s: String) {
def this(i: Int) = this("" + (i+2))
}
据我了解,构造函数不是继承的,并且不能像 Java 中那样使用 super
从子类调用辅助构造函数。
它们只是一个无用的工件还是这个结构有一些合理的用例?
Consider this code:
abstract class Foo(val s: String) {
def this(i: Int) = this("" + (i+2))
}
As far as I understand constructors aren't inherited and secondary constructors cannot be called from subclasses with super
like in Java.
Are they just a useless artifact or is there some sensible use-case for this construct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
子类的主构造函数必须调用超类的构造函数之一,但不一定是主类的构造函数。
The primary constructor of the subclass must call one of the constructor of the superclass, not necessarily the primary one.
除了@coubeatczech的答案之外,如果添加细化,您还可以创建抽象类(和特征)的实例,
尽管我在上面显示了一个空的细化(“{}”),但您通常会提供一些额外的定义,通常提供抽象成员的实现,
In addition to @coubeatczech's answer, you can also create instances of abstract classes (and traits) if you add a refinement,
Although I've show an empty refinement above ("{}") you would typically provide some additional definitions, often providing implementations for abstract members,