Home »
Kotlin »
Kotlin programs »
Kotlin class and object programs
Kotlin program | Example of constructor overloading
Kotlin | Constructor Overloading: Here, we are implementing a Kotlin program to demonstrate the example of constructor overloading.
Submitted by IncludeHelp, on June 03, 2020
Constructor Overloading
A Kotlin class has a primary constructor and one or more secondary constructors. When a class has more than one constructor, it will be known as constructor overloading.
Program for constructor overloading in Kotlin
package com.includehelp
//declare Class with Parameterized primary constructor
class ConstructorOverloading(len:Int){
//Init block, executed when class is instantiated,
//before secondary constructor body execution
init {
println("Init Block : $len")
}
//Secondary Constructor,
//delegate primary constructor with 'this' keyword
constructor() : this(10) {
println("Secondary Constructor No Parameter")
}
//Parameterized Secondary Constructor,
//delegate primary constructor with 'this' keyword
constructor(name:String):this(name.length){
println("Secondary Constructor with One Parameter : $name")
}
//Parameterized Secondary Constructor with two parameter,
//call same class non Parameterized secondary constructor
//using 'this()'
constructor(a:Int, b:Int) : this() {
println("Secondary Constructor With Two Parameter [$a, $b]")
}
}
//Main Function, Entry Point of Program
fun main(args:Array<String>){
//Create instance of class , with Primary Constructor
ConstructorOverloading(100)
//Create instance of class,
//with no argument secondary constructor
ConstructorOverloading()
//Create instance of class,
//with one argument secondary constructor
ConstructorOverloading("India")
//Create instance of class,
//with two argument secondary constructor
ConstructorOverloading(10,20)
}
Output:
Init Block : 100
Init Block : 10
Secondary Constructor No Parameter
Init Block : 5
Secondary Constructor with One Parameter : India
Init Block : 10
Secondary Constructor No Parameter
Secondary Constructor With Two Parameter [10, 20]