Traits
Traits are similar to interfaces in Java and are created using trait keyword.
Abstract Class
Abstract Class is similar to abstract classes in Java and are created using abstract keyword.
Example
Following is the program in Scala to show the usage of 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 meythod 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 { // Main method def main(args: Array[String]) { var obj = new Tester() obj.tutorials() obj.test() var obj1 = new TraitTester() obj1.tutorials() obj1.test() } }
Output
Abstract Class tutorial Welcome to Tutorialspoint Traits tutorials Welcome to Tutorialspoint
Following are some of the important differences between Traits and Abstract Classes in Scala.
Sr. No. | Key | Trait | Abstract Class |
---|---|---|---|
1 | Multiple inheritance | Trait supports multiple inheritance. | Abstract Class supports single inheritance only. |
2 | Instance | Trait can be added to an object instance. | Abstract class cannot be added to an object instance. |
3 | Constructor parameters | Trait cannot have parameters in its constructors. | Abstract class can have parameterised constructor. |
4 | Interoperability | Traits are interoperable with java if they don't have any implementation. | Abstract classes are interoperable with java without any restriction. |
5 | Stackability | Traits are stackable and are dynamically bound. | Abstract classes are not stacable and are statically bound. |