Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Classes, Traits and Objects

Inheritance and Abstract Classes

Learn Scala inheritance: extends, override, super, abstract classes and members, polymorphism, final, sealed and the Scala 3 open modifier, with diagrams and examples.

Inheritance lets a class reuse and specialize another class. A Dog is an Animal; a Circle is a Shape. In Scala you write extends, override members with the override keyword and mark incomplete classes as abstract. Scala 3 also adds the open modifier to say which classes are meant to be extended. Here you will learn these rules and the habits that keep hierarchies healthy. Scala is read-only; runnable Java and Kotlin demos run the same ideas.

extends and override

SCALA
class Animal(val name: String):
  def sound: String = "..."
  def describe: String = s"$name says $sound"

class Dog(name: String) extends Animal(name):
  override def sound: String = "woof"

class Cat(name: String) extends Animal(name):
  override def sound: String = "meow"

Dog("Rex").describe    // Rex says woof
Cat("Tom").describe    // Tom says meow
Animal("Thing").describe   // Thing says ...

Key points:

  • extends Animal(name) calls the parent's constructor with the arguments it needs.
  • override is mandatory when you replace a concrete member. The compiler catches typos: if you write override def sond, it complains that nothing is overridden.
  • describe is defined once in Animal and uses whichever sound the actual object has. That is polymorphism.
classDiagram
  class Animal {
    +name: String
    +sound: String
    +describe: String
  }
  Animal <|-- Dog
  Animal <|-- Cat

Dog and Cat inherit name and describe and override sound.

Subtype polymorphism lets one function handle many classes:

SCALA
def introduce(animals: List[Animal]): List[String] = animals.map(_.describe)

introduce(List(Dog("Rex"), Cat("Tom")))
// List(Rex says woof, Tom says meow)

Kotlin requires open on classes meant for inheritance, as this runnable demo shows:

Kotlin Inheritance and override (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Calling super

Inside an overriding member, super.member refers to the parent's version:

SCALA
class LoudDog(name: String) extends Dog(name):
  override def sound: String = super.sound.toUpperCase + "!"

LoudDog("Max").describe   // Max says WOOF!

Abstract classes

An abstract class cannot be instantiated. It may hold abstract members (declared without a body) that subclasses must implement, along with concrete members they share.

SCALA
abstract class Shape:
  def area: Double            // abstract: no body
  def name: String            // abstract
  def describe: String = f"$name with area $area%.2f"   // concrete

class Circle(r: Double) extends Shape:
  def area: Double = math.Pi * r * r
  def name: String = "circle"

class Square(side: Double) extends Shape:
  def area: Double = side * side
  def name: String = "square"

List(Circle(1.0), Square(2.0)).map(_.describe)
// List(circle with area 3.14, square with area 4.00)

Notes:

  • override is optional when you implement an abstract member (it is allowed, though).
  • Shape() is a compile error: "Shape is abstract; it cannot be instantiated".
  • Abstract classes can take constructor parameters; traits (next lesson) can too in Scala 3, but classes are preferred when you need a constructor with state.

Here is the same hierarchy in Java, runnable:

Java Abstract class in Java (comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Abstract vals and the initialization trap

You can declare abstract val and def members. Be careful with an abstract val read in the parent's constructor, because the subclass has not been initialized yet:

SCALA
abstract class Base:
  val label: String
  println(s"Base sees label = $label")     // runs BEFORE the subclass sets it

class Impl extends Base:
  val label = "ready"

Impl()    // prints "Base sees label = null"

The fix is to use def for abstract members that the parent may need during construction, or lazy val. Many style guides say: make abstract members def, because a subclass may implement a def with either a def or a val.

Preventing and controlling inheritance

Modifier Meaning
final class Cannot be extended
final def Cannot be overridden
sealed Can only be extended in the same file
open class Scala 3: explicitly designed for extension in other files

Scala 3 warns when you extend a class from another file unless that class is abstract, a trait, or marked open, which tells readers (and the compiler) which classes are designed for inheritance:

SCALA
open class Logger:
  def log(msg: String): Unit = println(msg)

sealed is a favourite for modelling a closed set of cases, because the compiler then checks that match expressions cover them all:

SCALA
sealed abstract class Weather
class Sunny extends Weather
class Rainy extends Weather

The chapter on pattern matching shows how sealed and case class combine for exhaustive matching.

Overriding vals, and the final rule

You can override a def with a val, but not the other way around: a val is a stable value, so a def (which can change between calls) is not allowed to replace it.

SCALA
class A:
  def n: Int = 1
class B extends A:
  override val n: Int = 2     // fine

Class hierarchy basics

  • Every class extends AnyRef (Java's Object) unless you say otherwise.
  • Scala has single inheritance for classes: a class has exactly one superclass, but it can mix in many traits. That is the topic of traits and mixins.
  • Use isInstanceOf[T] and asInstanceOf[T] rarely; pattern matching on type is clearer.
SCALA
val a: Animal = Dog("Rex")
a.isInstanceOf[Dog]      // true
a match
  case d: Dog => println("a dog")
  case _ => println("something else")

Prefer composition when in doubt

Inheritance couples a subclass tightly to its parent. A good test is "is-a" versus "has-a". A Car has an Engine; it is not an Engine. When behaviour is the only thing you share, prefer a trait or a function parameter over a deep hierarchy.

Common mistakes

  • Forgetting override and getting an error about an existing member.
  • Reading an abstract val in a superclass constructor and seeing null or 0.
  • Making deep hierarchies, which are hard to follow.
  • Extending a case class with another case class (not allowed, and discouraged).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is the override keyword mandatory?

    You must write override to replace a concrete inherited member; this catches typos and accidental overrides.
  2. 2. What is true of an abstract class?

    Abstract classes may mix concrete and abstract members but cannot be instantiated directly.
  3. 3. What does a sealed class restrict?

    sealed limits direct subclasses to the same source file, which enables exhaustiveness checks.
  4. 4. How many superclasses can a Scala class have?

    Scala has single class inheritance; multiple behaviour is reused through traits.

Summary

  • class B extends A inherits; override replaces a concrete member and super calls the parent's version.
  • Abstract classes declare members without bodies and cannot be instantiated.
  • Prefer abstract def over abstract val to avoid initialization-order surprises.
  • Control inheritance with final, sealed and Scala 3's open.
  • A class has one superclass; reuse extra behaviour through traits.

Next: Traits and Mixins