← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 6 of 7

Trait vs Abstract Class

In this page:

  1. Trait vs Abstract Class

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

markup
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()
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.