Primary and Secondary Constructors
Here’s a Kotlin code example that demonstrates primary and secondary constructors using a dog-related theme. I’ll extend the Dog class to show how to create Dog objects with different levels of information—using a primary constructor for full details and a secondary constructor for a simpler case.
** Also See Page 48 of the Lab Book
Code: Dogs with Primary and Secondary Constructors
// Dog class with primary and secondary constructors
class Dog(val name: String, var age: Int, var breed: String) {
// Primary constructor: Takes name, age, and breed
// Properties are defined directly with val/var in the constructor
init {
// Validation in init block (runs for all constructors)
if (age < 0) {
age = 0
println("Warning: Age was negative, set to 0 for $name")
}
println("Dog created: $name, $age years old, Breed: $breed")
}
// Secondary constructor: Takes only name, defaults age and breed
constructor(name: String) : this(name, 1, "Unknown") {
println("Secondary constructor used: Default age 1, breed Unknown")
}
// Method to display dog details
fun describe(): String {
return "Dog: $name, Age: $age, Breed: $breed"
}
}
// Main function to demonstrate both constructors
fun main() {
// Using primary constructor with full details
val peanut = Dog("Peanut", 9, "Beagle")
println(peanut.describe())
// Using secondary constructor with just a name
val stray = Dog("Stray")
println(stray.describe())
// Test with invalid age (caught by init block)
val puppy = Dog("Puppy", -2, "Labrador")
println(puppy.describe())
}
Output When Run
Dog created: Peanut, 9 years old, Breed: Beagle
Dog: Peanut, Age: 9, Breed: Beagle