The main purpose of constructor is to initialize the properties of a class. Constructor is called when we create the object of a class. In Kotlin we have two types of constructor – primary and secondary constructor. In this guide, we will learn primary and secondary constructor with example, we will also learn about initializer blocks.
Types of Constructor in Kotlin
1. Primary Constructor – Initialize the properties of class
2. Secondary Constructor – Initialize the properties of class, we can have additional initialization code inside secondary constructor.
1. Primary Constructor
A primary constructor is the easiest way to initialize the class. It is declared as part of the class header. In the following example we have declared a constructor (val name: String, var age: Int)
as part of the class header. This is our primary constructor that initializes the name
and age
properties (data members) of class Student
.
fun main(args: Array<String>) { //creating the object of class Student val stu = Student("Chaitanya", 31) println("Student Name: ${stu.name}") println("Student Age: ${stu.age}") } class Student(val name: String, var age: Int) { //This is my class. For now I am leaving it empty }
Output:
Default value in Kotlin constructor
We can also specify the default values in the Kotlin constructor like we did in the following example. Here we have specified the default student name as “Student” and default student age is 99.
We have created three objects of this class, one with both name and age, second object with only name and third object without name and age. As you can see in the output that default values are overriden by the values passed while creating objects of the class.
fun main(args: Array<String>) { //creating the object of class Student val stu = Student("Chaitanya", 31) val stu2 = Student("Chaitanya") val stu3 = Student() println("Name: ${stu.name} and Age: ${stu.age}") println("Name: ${stu2.name} and Age: ${stu2.age}") println("Name: ${stu3.name} and Age: ${stu3.age}") } class Student(val name: String = "Student", var age: Int = 99) { //This is my class. For now I am leaving it empty }
Output:
Initializer Block inside Kotlin Constructor
Lets learn to have additional initializer code inside the constructor of a class. In the following example we have a initializer block which we have declared inside constructor using init
. In this block we can have additional initialization logic.
fun main(args: Array<String>) { val stu = Student("Chaitanya", 31) val stu2 = Student("Chaitanya") val stu3 = Student() } class Student(val name: String = "Student", var age: Int = 99) { val stuName: String var stuAge: Int init{ if(name == "Student") { stuName = "NA" stuAge = 0 } else { stuName = name.toUpperCase() stuAge = age } println("Student Name is: $stuName") println("Student Age is: $stuAge") } }
Output:
2. Kotlin Secondary Constructor
Secondary constructor in Kotlin is created using the constructor
keyword. They play major role in inheritance. I recommend you to read the inheritance topic first before going through the secondary constructor.
Syntax of secondary constructor
class Student { constructor(name: String) { // code inside constructor } constructor(name: String, age: Int) { // code inside constructor } }
Example of secondary constructor
This is a simple example of how a secondary constructor is declared inside a class.
fun main(args: Array<String>){ val obj = Student ("Ajeet", 30) } class Student{ constructor(name: String, age: Int){ println("Student Name: ${name.toUpperCase()}") println("Student Age: $age") } }
Output:
Student Name: AJEET Student Age: 30
Calling one secondary constructor from another
In this example we have two secondary constructors, one with one parameter and other with two parameters. We are calling a constructor from another constructor using this
keyword.
fun main(args: Array<String>){ val obj = Student ("Ajeet") } class Student{ constructor(name: String): this(name, 0){ println("secondary constructor with one param") } constructor(name: String, age: Int){ println("secondary constructor with two param") println("Student Name: ${name.toUpperCase()}") println("Student Age: $age") } }
Output:
Kotlin Secondary Constructor example with parent and child class
In the following example we have two classes College
which is a parent class and a child class Student
. Here the child class secondary constructor is calling the parent class secondary constructor using the super
keyword.
fun main(args: Array<String>){ val stu = Student("Harry", 24) } open class College{ constructor(name: String, age: Int){ println("parent class constructor") println("Student Name: ${name.toUpperCase()}") println("Student Age: $age") } } class Student: College{ constructor(name: String, age: Int): super(name,age){ println("child class constructor") println("Student Name: $name") println("Student Age: $age") } }
Output:
parent class constructor Student Name: HARRY Student Age: 24 child class constructor Student Name: Harry Student Age: 24
Julio Talaverano says
Hi,
for the last example “Kotlin Secondary Constructor example with parent and child class” why do we need the parent and child class? When the anyway do always the same (without any condition) we also could put both functionalities in one class.
Or is it deliberately made so easy in order for us to understand the way it works?
Thanks
Julio
Tanishk Tripathi says
Hey!
Actually this is just a particular instance where a child class’s constructor is calling the parent’s constructor and Yes we can do this type of stunt in the same class(as you said). It’s just here to demonstrate a particular example of a situation between a parent child relation of the classes where the child’s constructor calls the parent’s.
Vijay says
Nice explanation sir, better than any youtube channel. Thank God, I found your website.