Constructors and Initialization
# CHAPTER 14
Constructors and Initialization
1. Chapter Introduction
In the previous chapter, we created aCar 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
initblock.
- 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):
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!
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.
5. Secondary Constructors (Overloading)
Sometimes you want to offer multiple ways to create an object. For example, creating aUser 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().*
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.7. Common Mistakes
-
Forgetting
valorvarin the Primary Constructor: If you writeclass Person(name: String),nameis just a temporary parameter passed to theinitblock. It is NOT saved as a property of the class! You must writeclass Person(val name: String)for it to become a permanent property.
8. Best Practices
-
Use Default Arguments: Avoid writing multiple
constructorblocks. Use default values in your primary constructor. It is significantly more idiomatic and concise.
9. Exercises
-
1.
Create a class
Productwith a primary constructor takingval name: Stringandvar price: Double.
-
2.
Add an
initblock that prints "Product created: [name]".
-
3.
Instantiate a
Productinmain()and print its price.
10. MCQs with Answers
Where is the Primary Constructor defined in Kotlin?
What keyword allows you to run executable code immediately when an object is instantiated?
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.
What is the keyword to define an additional constructor inside the class body?
What must every Secondary Constructor do?
What Kotlin feature largely eliminates the need to write multiple Secondary Constructors?
init blocks?
a) Yes, they execute in the order they appear b) No, only one is allowed
Answer: a) Yes.
When you call val p = Person("John"), which block of code runs first?
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.
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
initblock?
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 usingval 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 aDog 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.