Kotlin program | Example of Init in a Class

Kotlin | Init in a Class: Here, we are implementing a Kotlin program to demonstrate the example of init in a class.
Submitted by IncludeHelp, on June 08, 2020

'init' keyword

  • The primary constructor does not contain any code, so the initialization code can be placed in the initializer block.
  • Initializer block prefixed with init keyword.
  • There can be multiple init blocks in a class.
  • The initializer blocks execute the same order, as they appear in the class body.
  • Code inside the init blocks executed when class is instantiated.
  • All initializer blocks and property initializer is executed before the secondary constructor body.

Program demonstrate the example of Init in a Class in Kotlin

package com.includehelp

// Declaring Class with one Parameter 
// in Primary Constructor
class AutoMobile(model:String){
    // Declare Property
    private var model:String?=null

    // Initializer Block
    init{
        println("First initializer Block ")

        // Property initialization in init block
        this.model=model
    }

    // Property initialization in class body
    private val modelInUpper=model.toUpperCase()

    // Kotlin allow printing properties in the declaration
    // itself by using the also function
    private val modelLen = "Model Len: ${model.length}".also(::println)

    // Second Init Block
    init{
        println("Second initializer Block ")
        println("Model in Upper : $modelInUpper")
    }

    // Member Function
    fun printModel(){
        println("Model : $model")
    }
}

// Main, Function, Entry Point of Program
fun main(args: Array<String>){
    // Create Class Object
    val auto = AutoMobile("honda")
    // Call Method on AutoMobile Object
    auto.printModel()

    // Create Class Object
    val maruti = AutoMobile("maruti suzuki")
    // Call Method on AutoMobile Object
    maruti.printModel()
}

Output:

First initializer Block 
Model Len: 5
Second initializer Block 
Model in Upper : HONDA
Model : honda
First initializer Block 
Model Len: 13
Second initializer Block 
Model in Upper : MARUTI SUZUKI
Model : maruti suzuki


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.