🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Inheritance

Inheritance is a way for one class to take another class's fields and methods and add its own. The new class starts from what the first class already has instead of starting from nothing.

A child uses the parent methods

The Dog class extends Animal and adds nothing here. The greet method and the name field both come from the parent.

class Animal(val name: String):
  def greet: String = s"Hello, I am $name"

class Dog(name: String) extends Animal(name)

@main def main(): Unit =
  val rex = Dog("Rex")
  println(rex.name)
  println(rex.greet)

The child passes values up

The Dog line passes its name and age up to the Animal constructor. The label method of the parent then reads both fields.

class Animal(val name: String, val age: Int):
  def label: String = s"$name ($age)"

class Dog(name: String, age: Int) extends Animal(name, age)

@main def main(): Unit =
  val bella = Dog("Bella", 5)
  println(bella.label)
  println(bella.age)

Override replaces a method

Each child replaces the sound method of the parent with its own line. The override word marks each replacement.

class Animal(val name: String):
  def sound: String = "..."

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

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

@main def main(): Unit =
  val plain = Animal("Pip")
  val rex = Dog("Rex")
  val tom = Cat("Tom")
  println(plain.sound)
  println(rex.sound)
  println(tom.sound)

Example

class Animal(val name: String, val age: Int):
  def label: String = s"$name ($age)"
  def sound: String = "Quiet"

class Puppy(name: String, age: Int) extends Animal(name, age):
  override def sound: String = "Yip"

@main def main(): Unit =
  val pip = Puppy("Pip", 1)
  println(pip.label)
  println(pip.sound)
  println(pip.name)

Key points

  • Inheritance: one class takes the fields and methods of another class and adds its own.
  • Parent: the class whose fields and methods are taken by another class.
  • Child: the class that takes from a parent and can add or replace parts.
  • Extends: the word extends names the parent class after the child's own parameters.
  • Passing up: the child passes values up to the parent constructor in the extends line.
  • Override: a method that replaces a parent method is marked with the word override.
  • Inherited method: a method from the parent that the child keeps works on the child as it is.

In this example, the Puppy class passes its name and age up to the Animal constructor. The label method comes from the parent unchanged, so it prints the name with the age. The sound method is replaced with override, so the puppy prints Yip instead of Quiet.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

A child class replaces a method of its parent class. Which word must mark the new method?