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
Dog created: Stray, 1 years old, Breed: Unknown
Secondary constructor used: Default age 1, breed Unknown
Dog: Stray, Age: 1, Breed: Unknown
Warning: Age was negative, set to 0 for Puppy
Dog created: Puppy, 0 years old, Breed: Labrador
Dog: Puppy, Age: 0, Breed: Labrador
Explanation of the Code
Definition: class Dog(val name: String, var age: Int, var breed: String) Takes three parameters: name (immutable), age (mutable), and breed (mutable). These are directly declared as properties using val and var in the constructor. Usage: Dog("Peanut", 9, "Beagle") creates a dog with all details specified. Init Block: Runs after the primary constructor, validating age and printing a creation message. Definition: constructor(name: String) : this(name, 1, "Unknown") Takes only name and defaults age to 1 and breed to "Unknown". Uses : this() to call the primary constructor with these defaults. Adds a println to show it’s been used. Usage: Dog("Stray") creates a dog with minimal info, relying on defaults. Shared by both constructors—ensures age isn’t negative (sets it to 0 if it is). Prints a creation message for every Dog object, showing the constructor’s result. Returns a string with the dog’s details, used to verify the objects in main().