Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between Traits and Abstract Classes in Scala.
In Scala, both traits and abstract classes can contain abstract and non-abstract methods. Traits are similar to Java interfaces (with default methods), while abstract classes are similar to Java abstract classes. The key difference is that traits support multiple inheritance, while abstract classes support only single inheritance.
Traits
Traits are created using the trait keyword. They can contain both abstract and concrete methods. A class can mix in multiple traits using the with keyword, and traits can also be added to individual object instances at creation time.
Abstract Classes
Abstract classes are created using the abstract keyword. They can also contain both abstract and concrete methods. A class can extend only one abstract class. Unlike traits, abstract classes can have constructor parameters.
Example
The following example demonstrates both traits and abstract classes ?
trait SampleTrait {
// Abstract method
def test
// Non-Abstract method
def tutorials() {
println("Traits tutorials")
}
}
abstract class SampleAbstractClass {
// Abstract method
def test
// Non-abstract method
def tutorials() {
println("Abstract Class tutorial")
}
}
class Tester extends SampleAbstractClass {
def test() {
println("Welcome to Tutorialspoint")
}
}
class TraitTester extends SampleTrait {
def test() {
println("Welcome to Tutorialspoint")
}
}
object HelloWorld {
def main(args: Array[String]) {
var obj = new Tester()
obj.tutorials()
obj.test()
var obj1 = new TraitTester()
obj1.tutorials()
obj1.test()
}
}
The output of the above code is ?
Abstract Class tutorial Welcome to Tutorialspoint Traits tutorials Welcome to Tutorialspoint
Key Differences
| Feature | Trait | Abstract Class |
|---|---|---|
| Multiple Inheritance | Supported (mix in multiple traits with with) |
Not supported (extend only one class) |
| Object Instance | Can be added to an object at creation time | Cannot be added to an object instance |
| Constructor Parameters | Not allowed | Allowed |
| Java Interoperability | Only if no implementation code | Fully interoperable |
| Stackability | Stackable, dynamically bound | Not stackable, statically bound |
| Keyword | trait |
abstract class |
Conclusion
Use traits when you need multiple inheritance or want to add behavior to individual objects at creation time. Use abstract classes when you need constructor parameters or full Java interoperability. In Scala, traits are generally preferred for defining reusable, composable behavior.
