CodeBlanks Logo Icon CodeBlanks

Secondary constructor

Learn multiple constructors with secondary constructors.

Secondary constructor

When you need multiple constructors in a class, you use a secondary constructor. It starts with the constructor keyword and its body must delegate to another constructor with this(...).

Example: class Book(val title: String) { constructor(t: String, a: String) : this(t) { println(a) } }. The second constructor first calls the primary constructor via this(t), then runs its own body. Every secondary constructor must start with a this delegation.

The this(...) call

A secondary constructor delegates to another constructor with this(...) at the start of its body. The call must be the first statement. The primary constructor and init blocks run first, then the secondary body runs.

Example: constructor(name: String, age: Int) : this(name) { println(age) }. Here this(name) runs the primary constructor first, then the secondary body runs. This order guarantees that properties are always initialized.

Practice Add a secondary constructor to Book

Define a class named Book. Its primary constructor takes val title: String. Add a secondary constructor that takes title and author, delegates with this(title) and writes println("Author: $author") in its body. In main call the two-parameter constructor.

Starter code

Main.kt
// Define the Book class
// primary: val title: String
// secondary: title and author, delegating with this(title)
// call the two-parameter constructor in main

Sample solution

Main.kt
class Book(val title: String) {
    constructor(t: String, a: String) : this(t) {
        println("Author: $a")
    }
}

fun main() {
    val b = Book("Kotlin", "JetBrains")
}

Expected output

Author: JetBrains

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the parts of a secondary constructor

Term Meaning
constructor(t, a) Secondary signature
: this(t) Primary delegation
{ println(a) } Extra body
class Book(val title) Primary constructor

2 When is a secondary constructor used?

  • When the class has only one parameter
  • When primary constructors are forbidden
  • When different parameter combinations are needed for the same class Correct answer
  • When the class will not be inherited

Explanation: A secondary constructor is added when different parameter sets are needed.

3 Complete the secondary constructor body

Question
class Book(val title: String) {
    constructor(t: String, a: String) ____ this(t) {
        println(a)
    }
}
Answer
class Book(val title: String) {
    constructor(t: String, a: String) : this(t) {
        println(a)
    }
}

Explanation: The colon binds the this call.

All lessons in Intermediate