码迷,mamicode.com
首页 > 其他好文 > 详细

trait or abstract class?

时间:2017-09-29 16:28:53      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:dynamic   导致   must   without   pil   efi   general   stack   multi   

  • 首先你需要重用才需要考虑这个问题。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
  1. multiple, unrelated classes, make it a trait.
  2. If outside clients will only call into the behavior, instead of inheriting from it, then using a trait is fine.

 

  • 优先使用abstract class
  1. 如果你需要构造函数参数,使用抽象类。因为抽象类可以定义带参数的构造函数,而特质不行。例如,你不能说trait t(i: Int) {},参数i是非法的。
    1. Abstract classes can have constructor parameters as well as type parameters.
    2. Traits can have only type parameters. There was some discussion that in future even traits can have constructor parameters
  2. 对于与java互动:优先abstract class
    1. Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers.
    2. Traits are fully interoperable only if they do not contain any implementation code
  3.  compiled form分布的,有外部其他类继承
    1. 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.
  4. 需要高效率--不一定,在肯定trait导致bottleneck时可以使用abstract class
  5. in classes, super calls are statically bound, in traits, they are dynamically bound.
    1. If you write super.toString in a class, you know exactly which method implementation will be invoked.
    2. 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.

REFERENCE 

 stackoverflow: Scala特质 vs 抽象类 , 抽象类和特质的区别, and Scala编程: 用特质,还是不用特质?

http://www.artima.com/pins1ed/traits.html

trait or abstract class?

标签:dynamic   导致   must   without   pil   efi   general   stack   multi   

原文地址:http://www.cnblogs.com/yumanman/p/7611101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!