Home »
Kotlin »
Kotlin programs »
Kotlin class and object programs
Kotlin program | Companion object features
Kotlin | Companion Object Example: Here, we are implementing a Kotlin program to demonstrate the example of companion object features.
Submitted by IncludeHelp, on June 03, 2020
Companion object
Program for companion object features in Kotlin
package com.includehelp
//Declare class
class Car{
//class init block
init {
println("Init Block of Class")
}
//Make companion object
companion object {
//companion object init block
init {
println("Init Block of Companion object")
}
//property of companion object
val name="Tata Altroz !! "
//function in companion object
fun printName(){
println("Your Car name : $name")
}
}
}
//Main Function, Entry Point of Program
fun main(){
//Call method with Class name,
//without create Instance of class,
//like static method in java
Car.printName()
//access Property using class name
val nameLen = Car.name.length
println("Car Name Length : $nameLen")
}
Output
Init Block of Companion object
Your Car name : Tata Altroz !!
Car Name Length : 15