Javatpoint Logo
Javatpoint Logo

Kotlin Class and Object

Kotlin supports both object oriented programming (OOP) as well as functional programming. Object oriented programming is based on real time objects and classes. Kotlin also support pillars of OOP language such as encapsulation, inheritance and polymorphism.

Kotlin Class

Kotlin class is similar to Java class, a class is a blueprint for the objects which have common properties. Kotlin classes are declared using keyword class. Kotlin class has a class header which specifies its type parameters, constructor etc. and the class body which is surrounded by curly braces.

Syntax of Kotlin class declaration

In above example, class className is an empty constructor. It is generated by compiler automatically but if we want to provide a constructor, we need to write a constructor keyword followed by class name as:

Example of Kotlin class

The account class has three properties acc_no, name, amount and three member functions deposit(), withdraw(),checkBalance().

In Kotlin, property must be initialize or declare as abstract. In above class, properties acc_no initialize as 0, name as null and amount as 0f.

Kotlin Object

Object is real time entity or may be a logical entity which has state and behavior. It has the characteristics:

  • state: it represents value of an object.
  • behavior: it represent the functionality of an object.

Object is used to access the properties and member function of a class. Kotlin allows to create multiple object of a class.

Create an object

Kotlin object is created in two steps, the first is to create reference and then create an object.

Creating multiple object

Here obj1 and obj2 are reference and className() is an object.

Access class property and member function

Properties and member function of class are accessed by . operator using object. For example:

Let's create an example, which access the class property and member function using . operator.


Account no: 832345 holder :Ankit amount :1000.0

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA