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.
Note: A class can extend at most one class/abstract class, but mix in as many traits as needed -- that flexibility is usually the deciding factor.
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: