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

Overriding Methods

Overriding means a child class does an inherited job its own way, like a kid who follows Grandma's recipe with a twist. In Scala you must write the word override on purpose.

In this page:

  1. Overriding Methods
Syntax
scala
class ParentClass {
  def method_name(): Type = expression
}

class ChildClass extends ParentClass {
  override def method_name(): Type = expression
}

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())
}
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. Leaving out the override keyword, which gives an error because the method already exists in the parent.
  2. Changing the parameter list or return type in a way that does not match, so it overloads rather than overrides.
  3. Trying to override a final method or a val with a def, which is not allowed.
🔒

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.