Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Abstract Class and Trait [duplicate]

Possible Duplicate:
Scala traits vs abstract classes

What is the conceptual difference between abstract classes and traits?

like image 922
Red Hyena Avatar asked Jan 05 '10 11:01

Red Hyena


People also ask

What is the difference between a trait and an abstract class?

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.

What is the difference between abstract class and inheritance class?

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.

Can an abstract class extend a trait?

A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.

What is the difference between a trait and a mixin?

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.


2 Answers

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.

like image 126
Hans-Peter Störr Avatar answered Sep 21 '22 21:09

Hans-Peter Störr


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.

like image 40
Thomas Jung Avatar answered Sep 25 '22 21:09

Thomas Jung