ADVERTISEMENT
ADVERTISEMENT

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.