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:
Syntax
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
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())
}
Login to try C/C++/Java/PHP code in the editor
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
- Leaving out the
overridekeyword, which gives an error because the method already exists in the parent. - Changing the parameter list or return type in a way that does not match, so it overloads rather than overrides.
- Trying to override a
finalmethod or avalwith adef, which is not allowed.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: