← Back to Scala Course | Chapter 7: OOP Basics | Lesson 2 of 7

Constructors

In this page:

  1. Constructors

Constructors

A class's primary constructor is defined directly in its parameter list, and code in the class body (outside method definitions) runs as part of construction. Auxiliary constructors, defined with def this(...), provide alternate ways to construct an object, and must ultimately call the primary constructor. Most simple classes only need the primary constructor.

Note: Every auxiliary constructor (def this(...)) must eventually call the primary constructor, directly or through another auxiliary one.

Example: Constructors

markup
class Person(val name: String, val age: Int) {
  println(s"Creating a Person: $name")

  def this(name: String) = this(name, 0)
}

object Main extends App {
  val alice = new Person("Alice", 30)
  val baby = new Person("Baby")

  println(s"${alice.name}, ${alice.age}")
  println(s"${baby.name}, ${baby.age}")
}
🔒

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.