kotlin
Copy code
class Person(val name: String, var age: Int) {
// Primary constructor
constructor(name: String) : this(name, 0) {
println("Primary constructor called for $name with default age 0")
}
// Secondary constructor
constructor(name: String, vacayPreference: String) : this(name) {
println("Secondary constructor called for $name with vacation preference: $vacayPreference")
// Additional logic specific to the secondary constructor
if (vacayPreference.isNotEmpty()) {
println("$name prefers vacationing in $vacayPreference.")
}
}
fun printInfo() {
println("Name: $name, Age: $age")
}
}
fun main() {
val person1 = Person("Bob", 40)
person1.printInfo()
val person2 = Person("Charlie")
person2.printInfo()
val person3 = Person("Mike", "Hawaii")
person3.printInfo()
}
sql
Copy code
Primary constructor called for Bob with default age 0
Name: Bob, Age: 40
Primary constructor called for Charlie with default age 0
Name: Charlie, Age: 0
Primary constructor called for Mike with default age 0
Secondary constructor called for Mike with vacation preference: Hawaii
Mike prefers vacationing in Hawaii.
Name: Mike, Age: 0