Home »
Scala
Difference between Traits and Abstract Class in Scala
By IncludeHelp Last updated : October 26, 2024
Abstract Class in Scala
An Abstract Class in Scala is created using the abstract
keyword. It can contain both abstract and non-abstract methods. Multiple inheritances are not supported with abstract classes.
Syntax
abstract class ClassName {
def abstractMethod: Unit
def generalMethod(): Unit = {
}
}
Example
abstract class Bike {
// Declare speed as an abstract method
def speed(): Unit
def display(): Unit = {
println("This is my new Bike")
}
}
class Ninja400 extends Bike {
// Provide implementation for the abstract method
def speed(): Unit = {
println("Top Speed is 178 Kmph")
}
}
object MyObject {
def main(args: Array[String]): Unit = {
val obj = new Ninja400()
obj.display()
obj.speed()
}
}
Output
This is my new Bike
Top Speed is 178 Kmph
Traits in Scala
Traits in Scala are created using the trait
keyword. They can contain both abstract and non-abstract methods and fields. Traits are similar to interfaces in Java, allowing multiple inheritance and offering more powerful capabilities compared to their Java counterparts.
Syntax
trait trait_name{
}
Example
trait Bike {
// Define speed as a method with parentheses
def speed(): Unit
def display(): Unit = {
println("This is my new Bike")
}
}
class Ninja400 extends Bike {
// Provide implementation for the speed method
def speed(): Unit = {
println("Top Speed is 178 Kmph")
}
}
object MyObject {
def main(args: Array[String]): Unit = {
val obj = new Ninja400()
obj.display()
obj.speed()
}
}
Output
This is my new Bike
Top Speed is 178 Kmph
Difference between Abstract Class and Traits
The following table highlights the key differences between abstract classes and traits in Scala, based on their features, capabilities, and usage:
Abstract Class |
Traits |
Abstract classes do not support multiple inheritance; a class can extend only one. |
Traits allow multiple inheritances, enabling a class to inherit from multiple traits. |
Constructor parameters are allowed in abstract classes. |
Traits cannot have constructor parameters. |
Abstract class code is fully interoperable and can be instantiated directly. |
Trait code is interoperable until implemented and cannot be instantiated directly. |
Abstract classes cannot be added to object instances; they must be extended. |
Traits can be mixed into object instances for greater flexibility. |
Abstract classes can have both abstract and concrete methods. |
Traits can also have abstract and concrete methods, often for reusable behavior. |
Abstract classes can have fields with specific access modifiers. |
Traits have public fields that must be initialized in the implementing class. |