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

Overriding Methods

In this page:

  1. Overriding Methods

Overriding Methods

A subclass replaces an inherited method's behavior with override def methodName(...) = ..., and the override keyword is *mandatory* in Scala, unlike some languages where it's optional or implicit. This requirement catches accidental overrides (or accidental non-overrides due to a typo) at compile time. super.methodName(...) calls the parent's version from inside the override.

Warning: Omitting the override keyword when replacing an inherited method is a compile error in Scala, unlike languages where it's optional.

Example: Overriding Methods

markup
class Animal(val name: String) {
  def speak(): String = "..."
}

class Dog(name: String) extends Animal(name) {
  override def speak(): String = "Woof!"
}

object Main extends App {
  val rex = new Dog("Rex")
  println(rex.speak())
}
🔒

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.