Class and objects in Kotlin

In this tutorial, we will learn about class and objects in Kotlin. As we know Kotlin is a JVM based programming language and same as Java, Kotlin is an Object-Oriented Programming language. In simple words, Class is a blueprint for an object. For example, you have object student we can create a class for the student object which can have variables like stu_name, stu_class and some methods etc. We can create any number of objects of a class. The way to create a class in Kotlin is same as Java. Please check out the following Syntax to create a class in Kotlin.

class CLASS_NAME {
   // class Body
}

Creating a Class:

Same as Java there is a class keyword in Kotlin. Which we used to create a class in Kotlin. This class keyword followed by Class_Name. we can write any number of variables and methods in class according to requirements.  We can also control the visibility of the class members variables and methods using access specifiers. To understand this wisely please check out the following example program in which we will create a Student class.

Example Program:

class Student {
   // property (data member)
   private var name: String = "Ram"
   
   // member function
   fun showInfo(){
      print("Name: "+name)
   }
}

Creating an Object:

We can write any number of objects of the class. It is simple to create an object of the class in Kotlin. Please check out the following example program.

class Student {
   // property (data member)
   private var name: String = "Ram"
   
   // member function
   fun showInfo(){
      print("Name: "+name)
   }
}
fun main(args: Array<String>) {
   val obj = Student() // creating obj object of Student class
   obj.showInfo()
}

Output:

Name: Ram

 

Spread the love
Scroll to Top
×