📖 Scenario: You are creating a simple Kotlin class to represent a Book in a library system. Sometimes you know all the details about the book, and sometimes you only know the title and author.
🎯 Goal: Build a Kotlin class Book with a primary constructor and a secondary constructor to handle different ways of creating book objects.
📋 What You'll Learn
Create a class called Book with a primary constructor that takes title, author, and year.
Add a secondary constructor that takes only title and author, and sets year to 0.
Create two Book objects using both constructors.
Print the details of both books.
💡 Why This Matters
🌍 Real World
Secondary constructors let you create objects in different ways depending on the information you have, like when some details are missing or optional.
💼 Career
Understanding constructors is essential for Kotlin developers to write flexible and readable code, especially when working with data models in apps.
Progress0 / 4 steps
1
Create the Book class with a primary constructor
Create a Kotlin class called Book with a primary constructor that has three parameters: title of type String, author of type String, and year of type Int. Store these parameters as properties in the class.
Kotlin
Hint
Use class Book(val title: String, val author: String, val year: Int) to create the class with properties.
2
Add a secondary constructor to the Book class
Inside the Book class, add a secondary constructor that takes only title and author as parameters. This constructor should call the primary constructor and set year to 0.
Kotlin
Hint
Use constructor(title: String, author: String) : this(title, author, 0) inside the class.
3
Create two Book objects using both constructors
Create a variable called book1 using the primary constructor with "1984", "George Orwell", and 1949. Then create a variable called book2 using the secondary constructor with "Animal Farm" and "George Orwell".
Kotlin
Hint
Use val book1 = Book("1984", "George Orwell", 1949) and val book2 = Book("Animal Farm", "George Orwell").
4
Print the details of both books
Print the details of book1 and book2 in the format: Title: [title], Author: [author], Year: [year]. Use two separate println statements.
Kotlin
Hint
Use println("Title: ${book1.title}, Author: ${book1.author}, Year: ${book1.year}") and similarly for book2.
Practice
(1/5)
1. What is the main purpose of a secondary constructor in Kotlin?
easy
A. To create static methods
B. To replace the primary constructor completely
C. To provide additional ways to create an object with different parameters
D. To define functions inside a class
Solution
Step 1: Understand constructors in Kotlin
Kotlin classes can have a primary constructor and one or more secondary constructors to create objects.
Step 2: Role of secondary constructors
Secondary constructors allow creating objects with different sets of parameters, providing flexibility.
Final Answer:
To provide additional ways to create an object with different parameters -> Option C
Quick Check:
Secondary constructors = multiple ways to create objects [OK]
Hint: Secondary constructors add extra ways to create objects [OK]
Common Mistakes:
Thinking secondary constructors replace the primary constructor
Hint: Look for 'constructor' keyword without fun or init [OK]
Common Mistakes:
Adding 'fun' before constructor
Using 'secondary' keyword
Confusing with init blocks
3. What will be the output of the following Kotlin code?
class Person(val name: String) {
var age: Int = 0
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
fun main() {
val p = Person("Alice", 30)
println("Name: ${p.name}, Age: ${p.age}")
}
medium
A. Name: Alice, Age: 0
B. Name: Alice, Age: 30
C. Name: , Age: 30
D. Compilation error
Solution
Step 1: Understand constructor calls
The secondary constructor calls the primary constructor with this(name), initializing name.
Step 2: Assign age in secondary constructor
The secondary constructor sets this.age = age, so age becomes 30.
Final Answer:
Name: Alice, Age: 30 -> Option B
Quick Check:
Secondary constructor sets age correctly [OK]
Hint: Secondary constructor calls primary, then sets extra properties [OK]
Common Mistakes:
Assuming age stays 0
Thinking name is empty
Expecting compilation error
4. Identify the error in this Kotlin class with a secondary constructor:
A. Secondary constructor must call the primary constructor
B. Cannot assign to val property 'model'
C. Missing return type in secondary constructor
D. println cannot be used inside constructor
Solution
Step 1: Check secondary constructor rules
In Kotlin, a secondary constructor must delegate to the primary constructor using : this(...).
Step 2: Analyze given code
The secondary constructor does not call this(model), so it violates the rule.
Final Answer:
Secondary constructor must call the primary constructor -> Option A
Quick Check:
Secondary constructors require delegation [OK]
Hint: Always delegate secondary constructors to primary with ': this(...)' [OK]
Common Mistakes:
Forgetting to delegate to primary constructor
Trying to assign val property directly
Thinking println is disallowed
5. You want to create a Kotlin class Book with a primary constructor that takes title and a secondary constructor that also takes author. The secondary constructor should reuse the primary constructor and set author. Which code correctly implements this?
hard
A. class Book(val title: String) {
var author: String = "Unknown"
constructor(title: String, author: String) : this(title) {
this.author = author
}
}
B. class Book(val title: String, var author: String) {
constructor(title: String) {
this.title = title
this.author = "Unknown"
}
}
C. class Book(val title: String) {
constructor(title: String, author: String) {
this.title = title
this.author = author
}
}
D. class Book {
constructor(title: String) {
this.title = title
}
constructor(title: String, author: String) {
this.title = title
this.author = author
}
}
Solution
Step 1: Check primary constructor and property initialization
class Book(val title: String) {
var author: String = "Unknown"
constructor(title: String, author: String) : this(title) {
this.author = author
}
} defines primary constructor with title and a mutable author property with default value.