Inheritance Basics
Inheritance is a hand-me-down: a new class gets all it needs from an older one. The new class then adds its own extras.
In this page:
Syntax
class ParentClass(param: Type) {
// members
}
class ChildClass(param: Type) extends ParentClass(param) {
// additional members
}
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
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
- Forgetting to pass the constructor argument to the parent, as in
extends Animal, whenextends Animal(name)is required. - Declaring
class Dog(val name: String) extends Animal(name)and getting an error becausenameis already avalin the parent. - Trying to extend two classes with
extends A with Bwhere both are classes, when only traits can be mixed in.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: