Kotlin basics - Constructors

Kotlin basics - Constructors

In this article , lets understand how to use Primary constructor , Multiple constructors and init{...} block

First lets start with simple Student class

class Student {

    var studentFirstName: String = ""
    var studentLastName: String = ""
    var age: Int = 0

    fun printStudentName() {
        println("$studentFirstName $studentLastName")
    }

    fun printStudentAge() {
        println("$age")
    }

    fun printStudentInfo() {
        println("Name:$studentFirstName $studentLastName --- Age:$age")
    }

}

The above code is self explanatory which prints the basic info about students and the main class as follows

fun main() {
    val studentOne = Student()

    studentOne.studentFirstName = "Vignesh"
    studentOne.studentLastName = "Prabhu"
    studentOne.age = 29

    studentOne.printStudentName()
    studentOne.printStudentAge()
    studentOne.printStudentInfo()
}

Console O/P:
Vignesh Prabhu
29
Name:Vignesh Prabhu --- Age:29

Primary Constructor

The primary constructor can be defined as follows

class Student constructor(var studentFirstName: String,
                                             var studentLastName: String = "No Name",
                                             var age: Int) { ...}

and if we don't have to put an annotation / modifiers then it can be declared as following

class Student(var studentFirstName: String,
                                             var studentLastName: String = "No Name",
                                             var age: Int) { ...}

and the main class to use the primary constructor as follows

fun main() {
    val student = Student("Vignesh", "Prabhu", 29)
    student.printStudentName()
    student.printStudentAge()
    student.printStudentInfo()
}
Console O/P:
Vignesh Prabhu
29
Name:Vignesh Prabhu -------- Age:29

Multiple Constructor

  • We can use the constructor key word to declare any number of constructors in a call as follows
class Student(var studentFirstName: String,
                                  var studentLastName: String = "No Name",
                                  var age: Int,
                                  var isScholarShipApplied: Boolean) {

    constructor(studentFirstName: String, age: Int)
            : this(studentFirstName, "Unknown", age, false) {
        println("Called 2nd constructor")
    }

    constructor(studentFirstName: String)
            : this(studentFirstName, 0) {
        println("Called 3rd constructor")
    }

    ... }

In the above class we observe following things

  • there is one primary constructor and 2 secondary constructors .
  • each secondary constructor is having its own body

Now in the following code , lets use the third constructor with single parameter and observer the behavior

fun main() {
    val student = Student("Vignesh")
    student.printStudentInfo()
}
Console O/P:
Called 2nd constructor
Called 3rd constructor
Name:Vignesh Unknown -------- Age:0 --------- ScholarShipStatus:false

As we can observer in the console output , when we called the third constructor, the second constructor body is executed immediately and then the third constructor is triggered .

We can lock the constructors using modifiers like internal and protected

init block

  • init {...} block is called after primary constructor
  • multiple init blocks are possible and executed in the order of class definition .
class StudentInit(var studentFirstName: String, var studentLastName: String = "No Name", var age: Int) {

    constructor(studentFirstName: String) : this(studentFirstName, "No Name", 0) {
        println("2nd Constructor")
    }

    init {
        println("2nd init")
    }

    init {
        println("ist init")
    } 
...}

We can observer the foloowing things in the above code

  • first init{...} bolck is printing println("2nd init")
  • Second init{...} bolck is printing println("1st init")
  • secondary constructor with body

Now lets see the main class to use the above class

fun main() {

    val student = Student("Vignesh")
    student.printStudentInfo()
}

Console O/P:
2nd init
ist init
2nd Constructor
Name:Vignesh No Name -------- Age:0

So finally , I hope i made somebody understand constructors in Kotlin.

Please leave your comments to improve.

Enjoy Coding