trait or abstract class?
Posted satyrs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了trait or abstract class?相关的知识,希望对你有一定的参考价值。
- 首先你需要重用才需要考虑这个问题。If the behavior will not be reused, then make it a concrete class.
- 优先使用特质。一个类扩展多个特质是很方便的,但却只能扩展一个抽象类。
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.
- 优先使用trait
- multiple, unrelated classes, make it a trait.
- If outside clients will only call into the behavior, instead of inheriting from it, then using a trait is fine.
- 优先使用abstract class
- 如果你需要构造函数参数,使用抽象类。因为抽象类可以定义带参数的构造函数,而特质不行。例如,你不能说
trait t(i: Int) {}
,参数i
是非法的。- 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
- 对于与java互动:优先abstract class
- 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
- 以 compiled form分布的,有外部其他类继承
- 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.
- 需要高效率--不一定,在肯定trait导致bottleneck时可以使用abstract class
- 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.
- If you write
REFERENCE
stackoverflow: Scala特质 vs 抽象类 , 抽象类和特质的区别, and Scala编程: 用特质,还是不用特质?
http://www.artima.com/pins1ed/traits.html
以上是关于trait or abstract class?的主要内容,如果未能解决你的问题,请参考以下文章
快学Scala 第十九课 (trait的abstract override使用)
PHP 进阶之 抽象类(abstract)接口(interface)Trait(特征)
错误记录PyCharm 运行 Python 程序报错 ( PEP 8: E305 expected 2 blank lines after class or function definiti )(代
Hadoop遇到的坑运行hadoop自带的例子报错 Error: Could not find or load main class org.apache.hadoop.mapred.YarnCh(代