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

Inheritance Basics

In this page:

  1. Inheritance Basics

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()
}
🔒

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.