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
Program demonstrate the example of Init in a Class in Kotlin
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer