Q:

Kotlin program | Example of Init in a Class

belongs to collection: Kotlin Class and Object Programs

0

'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.

All Answers

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

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

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

total answers (1)

Kotlin program | Example of Interface... >>
<< Kotlin program | Example of inheritance...