Trait vs Abstract Class
In this page:
Trait vs Abstract Class
Choose an abstract class when you need constructor parameters or are modeling a strict single-inheritance "is-a" hierarchy; choose a trait when you want to mix reusable behavior into multiple, otherwise unrelated classes.
A class can extend only one abstract class but mix in any number of traits. In modern Scala, traits are the more commonly reached-for tool for sharing behavior, with abstract classes reserved for cases specifically needing constructor parameters or Java interop.
Example: Trait vs Abstract Class
abstract class Vehicle(val wheels: Int)
trait Honkable {
def honk(): Unit = println("Honk!")
}
class Car(wheels: Int) extends Vehicle(wheels) with Honkable
object Main extends App {
val car = new Car(4)
println(car.wheels)
car.honk()
}
Login to try C/C++/Java/PHP code in the editor
- Using an abstract class when the type needs multiple parents, since a class can extend only one.
- Giving a trait constructor parameters, which Scala 2 does not allow and Scala 3 permits only in a limited way.
- Picking a trait for something with a strict "is-a" relationship such as
Vehicle, when a class hierarchy communicates it better.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: