Difference between a "class" and an "object" in Kotlin


Kotlin is a statistically typed language. It has been built over Java, hence it inherits all the object-oriented programming concepts of Java. In this article, we will see the difference between a "class" and an "object" in Kotlin.

A "class" is a blueprint of a runtime entity and an "object" is its state, which includes both its behavior and state. In Kotlin, class declaration consists of a "class header" and a "class body" surrounded by curly braces, similar to Java. A general-purpose class definition looks like this −

// class Header
Class myClass {
   // class Body
}

There are different kinds of classed in Kotlin such as Inner class and Nested class.

Like Java, Kotlin also allows to create several objects of a class and you are free to include its class members and functions. We can control the visibility of the class member variables using different keywords.

Example

In this example, we will create a custom class and we will try to create different objects of that class.

class myClass {
   // property (data member)
   private var name: String = "Tutorialspoint"

   // member function
   fun printMe() {
      print("You are at the best Learning website: " +name)
   }
}

fun main(args: Array<String>) {
   // create object of myClass class
   val obj = myClass()
   obj.printMe()
}

Output

It will generate the following output:

You are at the best Learning website: Tutorialspoint

Updated on: 23-Nov-2021

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements