Possible Duplicate:
Scala traits vs abstract classes
What is the conceptual difference between abstract classes and traits?
Trait supports multiple inheritance. Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance.
These are two different concept and selections are based on the requirements. Abstraction hide the implementation details and only show the functionality. It reduce the code complexity. Inheritance create a class using a properties of another class.
A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.
Traits are compile-time external values (rather than code generated from an external source). The difference is subtle. Mixins add logic, Traits add data such as compile-time type information.
A class can only extend one superclass, and thus, only one abstract class. If you want to compose several classes the Scala way is to use mixin class composition: you combine an (optional) superclass, your own member definitions and one or more traits. A trait is restricted in comparison to classes in that it cannot have constructor parameters (compare the scala reference manual).
The restrictions of traits in comparison to classes are introduced to avoid typical problems with multiple inheritance. There are more or less complicated rules with respect to the inheritance hierarchy; it might be best to avoid a hierarchy where this actually matters. ;-) As far as I understand, it can only matter if you inherit two methods with the same signature / two variables with the same name from two different traits.
One aspect of traits is that they are a stackable. Allowing a constrainted form of AOP (around advice).
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
The resolution of super
reflects the linearization of the inheritance hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With