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

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:

  1. Inheritance Basics
Syntax
scala
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

markup
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()
}
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. Forgetting to pass the constructor argument to the parent, as in extends Animal, when extends Animal(name) is required.
  2. Declaring class Dog(val name: String) extends Animal(name) and getting an error because name is already a val in the parent.
  3. Trying to extend two classes with extends A with B where 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:

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.