Kotlin
class can have more than one secondary constructors.
How to define
secondary constructor?
You
should use the keyword ‘constructor’ to define secondary constructor.
Syntax
constructor(arguments){
}
Syntax
constructor(arguments){
}
ConstructorDemo.kt
class Employee { var firstName: String = "" var lastName: String = "" constructor(firstName: String) { this.firstName = firstName this.lastName = firstName } constructor(firstName: String, lastName: String) { this.firstName = firstName this.lastName = lastName } } fun printEmployee(emp: Employee) { println("firstName : ${emp.firstName}, lastName : ${emp.lastName}") } fun main(args: Array<String>) { var emp1 = Employee("Hareesh", "Seeram") var emp2 = Employee("Praneeth") printEmployee(emp1) printEmployee(emp2) }
Output
firstName : Hareesh, lastName : Seeram firstName : Praneeth, lastName : Praneeth
Primary
constructor must be called from secondary constructor explicitly. What I mean
is, if a class has primary constructor, then the secondary constructor must
delegate to the primary constructor either directly (or) indirectly using other
secondary constructors.
class
Employee(var firstName: String) {
....
....
constructor(fName: String, lName:
String) : this(fName) {
this.lastName = lName
this.id = ""
}
}
In
the above example, Employee class has a primary constructor, We are calling
primary constructor using 'this' keyword, while defining secondary constructor.
ConstructorDemo.kt
class Employee(var firstName: String) { var lastName: String = "" var id: String = "" constructor(fName: String, lName: String) : this(fName) { this.lastName = lName this.id = "" } constructor(fName: String, lName: String, id: String) : this(fName) { this.lastName = lName this.id = id } } fun printEmployee(emp: Employee) { println("id : ${emp.id}, firstName : ${emp.firstName}, lastName : ${emp.lastName}") } fun main(args: Array<String>) { var emp1 = Employee("Krishna") var emp2 = Employee("Hareesh", "Seeram") var emp3 = Employee("Praneeth", "Sai", "123") printEmployee(emp1) printEmployee(emp2) printEmployee(emp3) }
Output
id : , firstName : Krishna, lastName : id : , firstName : Hareesh, lastName : Seeram id : 123, firstName : Praneeth, lastName : Sai
No comments:
Post a Comment