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

Trait vs Abstract Class

This lesson helps you choose between a trait and an abstract class, like choosing between a skill card and a family blueprint. Traits mix in easily, while abstract classes suit shared setup.

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()
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using an abstract class when the type needs multiple parents, since a class can extend only one.
  2. Giving a trait constructor parameters, which Scala 2 does not allow and Scala 3 permits only in a limited way.
  3. 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:

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.