Friday, December 27, 2024
Google search engine
HomeGuest BlogsKotlin Constructor

Kotlin Constructor

A constructor is a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. A class needs to have a constructor and if we do not declare a constructor, then the compiler generates a default constructor. Kotlin has two types of constructors:

  1. Primary Constructor
  2. Secondary Constructor 

A class in Kotlin can have at most one primary constructor, and one or more secondary constructors. The primary constructor initializes the class, while the secondary constructor is used to initialize the class and introduce some extra logic.

Primary Constructor

The primary constructor is initialized in the class header, and goes after the class name, using the constructor keyword. The parameters are optional in the primary constructor.

class Add constructor(val a: Int, val b: Int) {
// code
}

The constructor keyword can be omitted if there is no annotations or access modifiers specified.  

class Add(val a: Int, val b: Int) {
// code
}

Kotlin program of primary constructor:

Kotlin




// main function
fun main(args: Array<String>)
{
    val add = Add(5, 6)
    println("The Sum of numbers 5 and 6 is: ${add.c}")
}
 
// primary constructor
class Add constructor(a: Int,b:Int)
{
    var c = a+b;
}


Output: 

The Sum of two numbers is: 11

Explanation:

When we create the object add for the class then the values 5 and 6 passes to the constructor. The constructor parameters a and b initialize with the parameters 5 and 6 respectively. The local variable c contains the sum of variables. In the main, we access the property of constructor using ${add.c}.

Primary Constructor with Initializer Block

The primary constructor cannot contain any code, the initialization code can be placed in a separate initializer block prefixed with the init keyword.

Kotlin program of primary constructor with initializer block 

What is init block? 

It acts as an initialiser block where member variables are initialised. This block gets executed whenever an instance of this class is created. There can be multiple init blocks and they are called in the order they are written inside the class.

Note: init blocks gets called before the constructor of this class is called.

Kotlin




class Person (val _name: String) {
    
   // Member Variables
   var name: String
 
   // Initializer Blocks
   init{
        println("This is first init block")
    }
     
    init{
        println("This is second init block")
    }
     
    init{
        println("This is third init block")
    }
    init {
      this.name = _name
      println("Name = $name")
   }
}
 
fun main(args: Array<String>) {
   val person = Person("Geeks")
}


Output: 

This is first init block
This is second init block
This is third init block
Name = Geeks

Explanation:

When the object person is created for the class Person, the value “Mahmood” is passed to the parameters name of the constructor. Two properties are declared in the class id and name.

Initializer block is executed at the time of object creation, and not only initializes the properties but also prints to the standard output.

Default value in primary constructor

Similar to function default values in functions, we can initialize the constructor parameters with some default values.

Kotlin program of default values in primary constructor:

Kotlin




fun main(args: Array<String>) {
    val emp = employee(18018, "Sagnik")
    // default value for emp_name will be used here
    val emp2 = employee(11011)
    // default values for both parameters
      // because no arguments passed
    val emp3 = employee()
}
 
class employee(emp_id : Int = 100 , emp_name: String = "abc") {
    val id: Int
    var name: String
 
    // initializer block
    init {
        id = emp_id
        name = emp_name
 
        print("Employee id is: $id, ")
        println("Employee name: $name")
        println()
    }
}


Output: 

Employee id is: 18018, Employee name: Sagnik
Employee id is: 11011, Employee name: abc
Employee id is: 100, Employee name: abc

Explanation:

Here, we have initialized the constructor parameters with some default values emp_id = 100 and emp_name = “abc”. When the object emp is created we passed the values for both the parameters, so it prints those values. 
But, at the time of object emp2 creation, we have not passed the emp_name so initializer block uses the default values and print to the standard output. 

Secondary Constructor

As mentioned above, Kotlin may have one or more secondary constructors. Secondary constructors allow initialization of variables and allow to provide some logic to the class as well. They are prefixed with the constructor keyword.

Kotlin program of implementing secondary constructor:

Kotlin




// main function
fun main(args: Array<String>)
{
    Add(5, 6)
}
 
// class with one secondary constructor
class Add
{
    constructor(a: Int, b:Int)
    {
        var c = a + b
        println("The sum of numbers 5 and 6 is: ${c}")
    }
}


Output: 

The sum of numbers 5 and 6 is: 11

Which secondary constructor will be called is decided by the compiler based on the arguments received. In the above program, we do not specify to invoke which constructor and compiler decides by itself.

Kotlin program of two secondary constructors in a class:  

Kotlin




fun main(args: Array<String>) {
    employee(18018, "Sagnik")
    employee(11011,"Praveen",600000.5)
}
class employee {
      constructor (emp_id : Int, emp_name: String ) {
          var id: Int = emp_id
          var name: String = emp_name
          print("Employee id is: $id, ")
          println("Employee name: $name")
          println()
      }
 
       constructor (emp_id : Int, emp_name: String ,emp_salary : Double) {
           var id: Int = emp_id
           var name: String = emp_name
           var salary : Double = emp_salary
           print("Employee id is: $id, ")
           print("Employee name: $name, ")
           println("Employee name: $salary")
       }
}


Output: 

Employee id is: 18018, Employee name: Sagnik
Employee id is: 11011, Employee name: Praveen, Employee name: 600000.5

Kotlin program of three secondary constructors in a class:

Kotlin




// main function
fun main(args: Array<String>)
{
    Add(5, 6)
    Add(5, 6, 7)
    Add(5, 6, 7, 8)
}
 
// class with three secondary constructors
class Add
{
    constructor(a: Int, b: Int)
    {
        var c = a + b
        println("Sum of 5, 6 = ${c}")
    }
    constructor(a: Int, b: Int, c: Int)
    {
        var d = a + b + c
        println("Sum of 5, 6, 7 = ${d}")
    }
    constructor(a: Int, b: Int, c: Int, d: Int)
    {
        var e = a + b + c + d
        println("Sum of 5, 6, 7, 8 = ${e}")
    }
}


Output: 

Sum of 5, 6 = 11
Sum of 5, 6, 7 = 18
Sum of 5, 6, 7, 8 = 26

Calling one secondary constructor from another

A secondary constructor may call another secondary constructor of the same class using this() function. In the below program, we have called another constructor using this(a,b,7) because invoking of that constructor requires three parameters.

Kotlin program of calling one constructor from another:

Kotlin




// main function
fun main(args: Array<String>)
{
    Add(5,6)
}
class Add {
    // calling another secondary using this
    constructor(a: Int,b:Int) : this(a,b,7) {
        var sumOfTwo = a + b
        println("The sum of two numbers 5 and 6 is: $sumOfTwo")
    }
     
    // this executes first
    constructor(a: Int, b: Int,c: Int) {
        var sumOfThree = a + b + c
        println("The sum of three numbers 5,6 and 7 is: $sumOfThree")
    }
}


Output:

The sum of three numbers 5,6 and 7 is: 18
The sum of two numbers 5 and 6 is: 11

Calling parent class secondary constructor from child class secondary constructor

We can call the secondary constructor of parent class from the child class using the super keyword. In the below program, we have shown the process of calling. 

As you can see here is a new keyword called open, an open class is an ordinary class that is open for extension. By default, when you write a class in Kotlin, it cannot be extended. Yes, inheritance is prevented by default. By declaring a class to be open, you tell the compiler: “I intend to extend this class”.

Kotlin




fun main(args: Array<String>) {
    Child(18018, "Sagnik")
}
 
open class Parent {
    constructor (emp_id: Int, emp_name: String, emp_salary: Double) {
        var id: Int = emp_id
        var name: String = emp_name
        var salary : Double = emp_salary
        println("Employee id is: $id")
        println("Employee name: $name")
        println("Employee salary: $salary")
        println()
    }
}
class Child : Parent {
    constructor (emp_id : Int, emp_name: String):super(emp_id,emp_name,500000.55){
        var id: Int = emp_id
        var name: String = emp_name
        println("Employee id is: $id")
        println("Employee name: $name")
    }
}


Output: 

Employee id is: 18018
Employee name: Sagnik
Employee salary: 500000.55
Employee id is: 18018
Employee name: Sagnik

Last Updated :
30 Sep, 2023
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Recent Comments