Object and Companion object In Kotlin

Object and Companion object In Kotlin

There are some keywords in each programming language that makes the lives of developers hard and In Kotlin the two keywords object and companion object are one of those keywords.

Before talking about object and companion object, I want to talk about singleton in Kotlin. As you might know, whenever we make a class, we can make many instances of that class and access the members of the class but in the case of the singleton class, we have just one instance of the singleton class in the whole application.

for example, if there is class Student then there exists only one object for this class by default which is created Internally. In simple words we cannot create object like student1, student2, etc for Student class.

In Java, Singletons are defined using static variables and methods. visit here to read more about singletons in java But In Kotlin there is no keyword like static and the single instance is created internally from object declarations and companion objects by the Kotlin compiler.

Object

In Kotlin we declare objects which act a class that contains static members without using static keyword and when the program runs, Kotlin simply creates a singleton object of that class.

Object declaration code snippet

object Person {
   var name: String = "Donald"   // Behaves as a static variable
    fun greet(): String {                // Behaves as a static method
        return "Hey ${this.name}"
    }
}
fun main(args: Array<String>) {
    val greeting: String
   /* Calling without creating Instance of person because Kotlin by default 
    creates an singleton instance for Person object 
   */
    Person.name = "Joe"           
    greeting = Person.greet()   
    println(greeting)
}
When you run the program, the output will be:
Hey Joe

The Person object can also inherit properties from a superclass and we can override the properties and methods of the superclass in our person object and call those properties and methods anywhere without making the object of the superclass.

open fun superClassMethod(){
        println("I am  the member of super class")
    }
}

object Person: superclass() {
   var name: String = "Donald"

    fun greet(): String {
        return "Hey ${this.name}"
    }
    // currently behaving as STATIC method
    override fun superClassMethod(){    
        // default implementation of inherited method  
        super.superClassMethod() 
        println("I am also the member of person class")
    }

}

fun main(args: Array<String>) {
    val greeting: String
    Person.name = "Joe"
    greeting = Person.greet()
    println(greeting)
    Person.superClassMethod()
}
When you run the program, the output will be:
Hey Joe
I am a member of superclass
I am also a member of the person class

Companion Object

companion object is the same as object but declared within a class.

The name of the companion object can be omitted, in which case the name Companion will be used:

class Person {
    companion object  {
        var name: String = "Donald"   
        fun greet(): String {                 
            return "Hey ${this.name}"
        }
    }
}

As we discussed previously the members of the object class only behaves like static variable and static methods respectively but on the JVM you can have members of companion objects generated as real static methods and fields if you use the @JvmStatic annotation

class Person {
    companion object  {
        var name: String = "Donald"   

        @JvmStatic 
        fun greet(): String {                 
            return "Hey ${this.name}"
        }
    }
}

Accessing the members of companion object: Members of the companion object can be called by using simply the class name as the qualifier

fun main(args: Array<String>) {
    val greeting: String
    Person.name = "Joe"           
    greeting = Person.greet()   
    println(greeting)
}
When you run the program, the output will be:
Hey Joe

Summary of Object and Companion Object

  1. when we use keyword object Kotlin internally creates a class and an object/Instance.

  2. These objects

    • can have properties, methods and initializers
    • cannot have constructors as we cannot create Instance/objects manually
    • can have a superclass
  3. Companion objects is same as object but declared within a class