BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Kotlin Constructors with examples

Last Updated: March 11, 2019 by Chaitanya Singh | Filed Under: Kotlin Tutorial

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

Kotlin Constructors
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:
Kotlin constructor example

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:
Default value in Kotlin constructor

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:
Initializer Block inside Kotlin Constructor

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

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
❮ PreviousNext ❯

Top Related Articles:

  1. Kotlin Nested and Inner Class with examples
  2. Kotlin Keywords, Soft Keywords and Identifiers
  3. Kotlin Class and Objects – Object Oriented Programming (OOP)
  4. Kotlin Abstract Class with examples
  5. Kotlin Interfaces with examples

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Julio Talaverano says

    October 6, 2019 at 2:53 PM

    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

    Reply
    • Tanishk Tripathi says

      December 6, 2020 at 4:05 PM

      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.

      Reply
  2. Vijay says

    March 11, 2020 at 7:38 AM

    Nice explanation sir, better than any youtube channel. Thank God, I found your website.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Kotlin Tutorial

  • Kotlin Tutorial
  • Kotlin in Eclipse IDE
  • Kotlin in IntelliJ
  • First Kotlin Program
  • Kotlin Keywords
  • Kotlin Variables
  • Kotlin Type Casting
  • Kotlin operators
  • Kotlin Input/Output
  • Kotlin Comments

Kotlin String

  • Kotlin String

Kotlin Array

  • Kotlin Array
  • Kotlin Range

Control Flow

  • Kotlin if expression
  • Kotlin when expression
  • Kotlin for loop
  • Kotlin while loop
  • Kotlin do-while loop
  • Kotlin continue
  • Kotlin break

Kotlin Function

  • Kotlin Function
  • Kotlin Recursion
  • Kotlin default and named arguments
  • Lambda functions
  • Higher Order Function

Exception Handling

  • Exception Handling
  • Kotlin try catch
  • Multiple catch blocks
  • Nested try catch
  • Throw keyword
  • Kotlin try expression

Kotlin OOP

  • Class and Objects
  • Kotlin Constructors
  • Kotlin Inheritance
  • Visibility Modifiers
  • Kotlin abstract class
  • Kotlin Interfaces
  • Nested and Inner Class
  • Kotlin Data Class
  • Kotlin Sealed Class

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap