Inheritance Basics
In this page:
Inheritance Basics
A class inherits from another with class Dog(name: String) extends Animal(name), gaining all of the parent's non-private members. This models an "is-a" relationship, like a Dog being a kind of Animal. Scala only supports single inheritance for classes -- a class can extend just one direct superclass, though traits (covered later) offer another way to share behavior.
Note: Scala supports single class inheritance only -- use traits when you need to combine behavior from multiple sources.
Example: Inheritance Basics
class Animal(val name: String) {
def eat(): Unit = println(s"$name is eating")
}
class Dog(name: String) extends Animal(name) {
def bark(): Unit = println(s"$name says Woof!")
}
object Main extends App {
val rex = new Dog("Rex")
rex.eat()
rex.bark()
}
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: