Q:

Kotlin program | Example of constructor overloading

belongs to collection: Kotlin Class and Object Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program | Example of Primary Constructor... >>
<< Kotlin program | Example of compile-time constant...