Skip to main content
Kotlin Basics
CHAPTER 14 Beginner

Constructors and Initialization

Updated: May 18, 2026
5 min read

# CHAPTER 14

Constructors and Initialization

1. Chapter Introduction

In the previous chapter, we created a Car object and then manually set its properties one by one on subsequent lines. This is tedious and error-prone. What if an object requires specific data to function properly? We should force the developer to provide that data the moment the object is created. We do this using Constructors.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define a Primary Constructor.
  • Automatically declare properties inside the constructor.
  • Run setup code using the init block.
  • Define Secondary Constructors (Constructor Overloading).

3. The Primary Constructor

A constructor is a special function that is automatically called when an object is instantiated. In Kotlin, the Primary Constructor is written directly into the class header!

Verbose Way (Similar to Java):

kotlin
123
class Person constructor(firstName: String) {
    var name: String = firstName // Assign the parameter to the property
}

The Kotlin Way (Concise): Kotlin allows you to declare properties directly in the constructor by adding val or var before the parameter name. This eliminates boilerplate!

kotlin
123456789
// The Primary Constructor is right here in the parentheses!
class Person(val name: String, var age: Int)

fun main() {
    // We MUST pass "Alice" and 28 when creating the object
    val user = Person("Alice", 28)
    
    println("${user.name} is ${user.age}")
}

4. The init Block

The Primary Constructor cannot contain any actual executable code (like println or if statements). If you need to run setup logic immediately when the object is created, you put it inside an init block.
kotlin
1234567891011121314151617
class BankAccount(val owner: String, startingBalance: Double) {
    var balance: Double = startingBalance

    // This runs automatically when the object is created!
    init {
        println("Initializing account for $owner...")
        if (balance < 0) {
            println("Warning: Account opened with negative balance!")
            balance = 0.0
        }
    }
}

fun main() {
    val myAccount = BankAccount("Bob", -50.0)
    println("Final Balance: $${myAccount.balance}")
}

5. Secondary Constructors (Overloading)

Sometimes you want to offer multiple ways to create an object. For example, creating a User with just an email, OR creating a User with an email and a phone number. You can define additional constructors inside the class body using the constructor keyword.

*Rule: Every secondary constructor MUST call the primary constructor using this().*

kotlin
1234567891011121314
class User(val email: String) { // Primary Constructor
    var phone: String = "Not Provided"

    // Secondary Constructor
    constructor(email: String, phone: String) : this(email) {
        this.phone = phone
        println("Secondary constructor used!")
    }
}

fun main() {
    val u1 = User("admin@test.com") // Calls Primary
    val u2 = User("user@test.com", "555-1234") // Calls Secondary
}

6. Kotlin's Better Way: Default Arguments

While Secondary Constructors exist, they are rarely used in Kotlin! Why? Because Kotlin's Default Arguments (which we learned in Chapter 9) solve this problem much more cleanly.
kotlin
1234567
// This ONE line replaces multiple secondary constructors!
class User(val email: String, var phone: String = "Not Provided")

fun main() {
    val u1 = User("admin@test.com") 
    val u2 = User("user@test.com", "555-1234") 
}

7. Common Mistakes

  • Forgetting val or var in the Primary Constructor: If you write class Person(name: String), name is just a temporary parameter passed to the init block. It is NOT saved as a property of the class! You must write class Person(val name: String) for it to become a permanent property.

8. Best Practices

  • Use Default Arguments: Avoid writing multiple constructor blocks. Use default values in your primary constructor. It is significantly more idiomatic and concise.

9. Exercises

  1. 1. Create a class Product with a primary constructor taking val name: String and var price: Double.
  1. 2. Add an init block that prints "Product created: [name]".
  1. 3. Instantiate a Product in main() and print its price.

10. MCQs with Answers

Question 1

Where is the Primary Constructor defined in Kotlin?

Question 2

What keyword allows you to run executable code immediately when an object is instantiated?

Q3. If you declare class Car(model: String), can you access myCar.model later? a) Yes b) No, because model is missing val or var, so it is not saved as a class property Answer: b) No, it is not saved as a class property.
Question 4

What is the keyword to define an additional constructor inside the class body?

Question 5

What must every Secondary Constructor do?

Question 6

What Kotlin feature largely eliminates the need to write multiple Secondary Constructors?

Q7. Can a class have multiple init blocks? a) Yes, they execute in the order they appear b) No, only one is allowed Answer: a) Yes.
Question 8

When you call val p = Person("John"), which block of code runs first?

Q9. Is the constructor keyword mandatory for the Primary Constructor? a) Yes, always b) No, it can usually be omitted (e.g., class Person(val name: String)) Answer: b) No, it can usually be omitted.
Question 10

Why are constructors important?

11. Interview Questions

  • Q: Explain how Kotlin handles constructor overloading differently than Java. (Answer: While Kotlin supports Secondary Constructors, it strongly encourages using Default Arguments in the Primary Constructor, reducing boilerplate code massively).
  • Q: What is the purpose of the init block?

12. Summary

Constructors are the gateway to creating objects. By moving the Primary Constructor into the class header and allowing properties to be declared inline using val or var, Kotlin removes enormous amounts of boilerplate code associated with Java initialization. The init block provides a safe space to execute validation logic upon creation.

13. Next Chapter Recommendation

Now we know how to create independent classes. But what if a Dog class and a Cat class share similar traits like age and eat()? In Chapter 15: Inheritance in Kotlin, we will learn how to share code between classes and build parent-child hierarchies.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·