使用抽象类而不是特质的优点是什么?

发布于 2025-02-04 15:33:57 字数 51 浏览 2 评论 0原文

使用抽象类代替性状(除了表现)的优点是什么?在大多数情况下,似乎可以将抽象类替换为特征。

What is the advantage of using an abstract class instead of a trait (apart from performance)? It seems like abstract classes can be replaced by traits in most cases.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

你的笑 2025-02-11 15:33:57

我可以想到两个差异

  1. 抽象类可以具有构造函数参数以及类型参数。特征只能具有类型参数。有一些讨论是,即将将来,即使特征也可以具有构造函数参数
  2. 摘要类别与Java完全互操作。您可以在没有任何包装器的情况下从Java代码中调用它们。只有当特征不包含任何实施代码时,特征才完全可互操作

I can think of two differences

  1. Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. There was some discussion that in future even traits can have constructor parameters
  2. Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are fully interoperable only if they do not contain any implementation code
以歌曲疗慰 2025-02-11 15:33:57

在Scala中有一个章节,称为“特征,还是特征?” 解决这个问题。由于第一版可以在线提供,因此我希望可以在这里引用整个内容。 (任何严重的Scala程序员都应购买这本书):

每当您实施可重复使用的行为集合时,您都会
必须确定您要使用特质还是抽象类。
没有坚定的规则,但是本节包含一些指南
考虑。

如果行为不会重复使用,则将其作为具体类。它
毕竟不是可重复使用的行为。

如果可以在多个无关类中重复使用,则将其作为特征。
只能将特征混合到类层次结构的不同部分。

如果您想从Java代码中继承它,请使用抽象类。
由于具有代码的特征没有密切的Java类似物,因此往往是
尴尬地从Java类中继承的特质。从a继承
同时,Scala类就像从Java类继承一样。
作为一个例外,只有抽象成员的Scala特征翻译
直接到Java界面,因此您应该随意定义这样的
即使您期望Java代码从中继承,特征也是如此。请参阅第29章
有关与Java和Scala一起工作的更多信息。

如果您打算以编译形式分配,并且期望在外面
撰写从中继承的课堂的小组,您可能会倾向于
使用抽象类。问题是,当特质获得或失败时
成员,从中继承的任何类
他们没有改变。如果外部客户只会打电话给
行为,而不是从中继承它,而是使用特征是可以的。

如果效率非常重要,请倾向于使用类。大多数爪哇
runtimes将类成员的虚拟方法调用速度更快
操作比接口方法调用。特征被编译为
界面,因此可能支付略有性能开销。
但是,只有在您知道特征的情况下才能做出选择
在所讨论的
而是使用类实际上解决了问题。

如果您仍然不知道在考虑以上之后,请先开始
使它成为一个特征。您可以随时以后再更改,一般可以
使用特质可以使更多的选项打开。

正如@mushtaq Ahmed所提到的那样,特征不能将任何参数传递给类的主要构造函数。

另一个区别是super的处理。

类和特征之间的另一个区别是,在类中,super调用在静态绑定中是固定绑定的,在特征中,它们是动态绑定的。如果您在类中编写super.tostring,则确切知道将调用哪种方法实现。但是,当您在特征中写同一件事时,当您定义特质时,要调用超级呼叫的方法是不确定的。

请参阅其余的第12章,有关更多详细信息。

编辑1(2013):

与特征相比,抽象类的行为方式存在细微的差异。线性化规则之一是它保留了类的继承层次结构,该类别倾向于在链条后期推动抽象类,而特征可以愉快地混合在一起。在某些情况下,实际上最好是在类线性化的后面位置。 ,因此可以将抽象类用于此。参见 scala 中的class linearization(mixin Order)。

编辑2(2018):

从Scala 2.12开始,特质的二进制兼容性行为已经改变。在2.12之前,将成员添加或删除成员在特征中需要重新编译所有继承特征的类,即使这些类未更改。这是由于特征在JVM中编码的方式。

从Scala 2.12开始,特征,因此要求放松了一下。如果特征执行以下任何内容,则其子类仍需要重新编译:

  • 定义字段(valvar,但是常数是可以的 - 最终val没有结果类型)
  • 调用超级
  • 主体中的初始化语句
  • 扩展类
  • 依靠线性化在正确的Supertrait中找到实现

,但是如果特征没有,您现在可以在不破坏二进制兼容性的情况下进行更新。

There's a section in Programming in Scala called "To trait, or not to trait?" which addresses this question. Since the 1st ed is available online, I'm hoping it's OK to quote the whole thing here. (Any serious Scala programmer should buy the book):

Whenever you implement a reusable collection of behavior, you will
have to decide whether you want to use a trait or an abstract class.
There is no firm rule, but this section contains a few guidelines to
consider.

If the behavior will not be reused, then make it a concrete class. It
is not reusable behavior after all.

If it might be reused in multiple, unrelated classes, make it a trait.
Only traits can be mixed into different parts of the class hierarchy.

If you want to inherit from it in Java code, use an abstract class.
Since traits with code do not have a close Java analog, it tends to be
awkward to inherit from a trait in a Java class. Inheriting from a
Scala class, meanwhile, is exactly like inheriting from a Java class.
As one exception, a Scala trait with only abstract members translates
directly to a Java interface, so you should feel free to define such
traits even if you expect Java code to inherit from it. See Chapter 29
for more information on working with Java and Scala together.

If you plan to distribute it in compiled form, and you expect outside
groups to write classes inheriting from it, you might lean towards
using an abstract class. The issue is that when a trait gains or loses
a member, any classes that inherit from it must be recompiled, even if
they have not changed. If outside clients will only call into the
behavior, instead of inheriting from it, then using a trait is fine.

If efficiency is very important, lean towards using a class. Most Java
runtimes make a virtual method invocation of a class member a faster
operation than an interface method invocation. Traits get compiled to
interfaces and therefore may pay a slight performance overhead.
However, you should make this choice only if you know that the trait
in question constitutes a performance bottleneck and have evidence
that using a class instead actually solves the problem.

If you still do not know, after considering the above, then start by
making it as a trait. You can always change it later, and in general
using a trait keeps more options open.

As @Mushtaq Ahmed mentioned, a trait cannot have any parameters passed to the primary constructor of a class.

Another difference is the treatment of super.

The other difference between classes and traits is that whereas in classes, super calls are statically bound, in traits, they are dynamically bound. If you write super.toString in a class, you know exactly which method implementation will be invoked. When you write the same thing in a trait, however, the method implementation to invoke for the super call is undefined when you define the trait.

See the rest of Chapter 12 for more details.

Edit 1 (2013):

There is a subtle difference in the way abstract classes behaves compared to traits. One of the linearization rules is that it preserves the inheritance hierarchy of the classes, which tends to push abstract classes later in the chain while traits can happily be mixed in. In certain circumstances, it's actually preferable to be in latter position of the class linearization, so abstract classes could be used for that. See constraining class linearization (mixin order) in Scala.

Edit 2 (2018):

As of Scala 2.12, trait's binary compatibility behavior has changed. Prior to 2.12, adding or removing a member to the trait required recompilation of all classes that inherit the trait, even if the classes have not changed. This is due to the way traits were encoded in JVM.

As of Scala 2.12, traits compile to Java interfaces, so the requirement has relaxed a bit. If the trait does any of the following, its subclasses still require recompilation:

  • defining fields (val or var, but a constant is ok – final val without result type)
  • calling super
  • initializer statements in the body
  • extending a class
  • relying on linearization to find implementations in the right supertrait

But if the trait does not, you can now update it without breaking binary compatibility.

醉生梦死 2025-02-11 15:33:57

无论值得什么值,Odersky等人的

For whatever it is worth, Odersky et al's Programming in Scala recommends that, when you doubt, you use traits. You can always change them into abstract classes later on if needed.

傲鸠 2025-02-11 15:33:57

除了您不能直接扩展多个抽象类的事实,但是您可以将多个特征混合到一个类中,还值得一提的是特征是可堆叠的,因为特征中的超级呼叫是动态绑定的(它是在以前混合的类或特征当前一个)。

中的差异之间的差异:

trait A{
    def a = 1
}

trait X extends A{
    override def a = {
        println("X")
        super.a
    }
}  


trait Y extends A{
    override def a = {
        println("Y")
        super.a
    }
}

scala> val xy = new AnyRef with X with Y
xy: java.lang.Object with X with Y = $anon$1@6e9b6a
scala> xy.a
Y
X
res0: Int = 1

scala> val yx = new AnyRef with Y with X
yx: java.lang.Object with Y with X = $anon$1@188c838
scala> yx.a
X
Y
res1: Int = 1

Other than the fact that you cannot directly extend multiple abstract classes, but you can mixin multiple traits into a class, it's worth mentioning that traits are stackable, since super calls in a trait are dynamically bound (it is referring a class or trait mixed before current one).

From Thomas's answer in Difference between Abstract Class and Trait:

trait A{
    def a = 1
}

trait X extends A{
    override def a = {
        println("X")
        super.a
    }
}  


trait Y extends A{
    override def a = {
        println("Y")
        super.a
    }
}

scala> val xy = new AnyRef with X with Y
xy: java.lang.Object with X with Y = $anon$1@6e9b6a
scala> xy.a
Y
X
res0: Int = 1

scala> val yx = new AnyRef with Y with X
yx: java.lang.Object with Y with X = $anon$1@188c838
scala> yx.a
X
Y
res1: Int = 1
筱武穆 2025-02-11 15:33:57

在扩展抽象类时,这表明子类是类似的。我认为,在使用特征时,情况并非如此。

When extending an abstract class, this shows that the subclass is of a similar kind. This is not neccessarily the case when using traits, I think.

眼前雾蒙蒙 2025-02-11 15:33:57

In Programming Scala the authors say that abstract classes make a classical object oriented "is-a" relationship while traits are a scala-way of composition.

怂人 2025-02-11 15:33:57

抽象类可以包含行为 - 它们可以用构造函数args(特征不能)参数化并代表一个工作实体。特征相反,只表示一个功能的一个功能。

Abstract classes can contain behaviour - They can parameterized with constructor args (which traits can't) and represent a working entity. Traits instead just represent a single feature, an interface of one functionality.

绿萝 2025-02-11 15:33:57
  1. 一个类可以从多个特征继承,但只有一个抽象类。
  2. 抽象类可以具有构造函数参数以及类型参数。特征只能具有类型参数。例如,您不能说特质t(i:int){}; i参数是非法的。
  3. 抽象类与Java完全互操作。您可以在没有任何包装器的情况下从Java代码中调用它们。只有当特征不包含任何实现代码时,才能完全互操作。
  1. A class can inherit from multiple traits but only one abstract class.
  2. Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. For example, you can’t say trait t(i: Int) { }; the i parameter is illegal.
  3. Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are fully interoperable only if they do not contain any implementation code.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文