Overriding Methods
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: