Difference between Traits and Abstract Classes in Scala.

ScalaJavaObject Oriented ProgrammingProgramming

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

 Live Demo

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.KeyTraitAbstract Class
1Multiple inheritanceTrait supports multiple inheritance.Abstract Class supports single inheritance only.
2InstanceTrait can be added to an object instance.Abstract class cannot be added to an object instance.
3Constructor parametersTrait cannot have parameters in its constructors.Abstract class can have parameterised constructor.
4InteroperabilityTraits are interoperable with java if they don't have any implementation.Abstract classes are interoperable with java without any restriction.
5StackabilityTraits are stackable and are dynamically bound.Abstract classes are not stacable and are statically bound.
raja
Published on 15-Apr-2020 11:20:35
Advertisements