Kotlin Class and Objects: In this tutorial, you’ll be acquainted with Object-oriented programming in Kotlin. You’ll learn what a class is, the means by which to create objects and use them in your program.

Kotlin supports both object-oriented programming (OOP) just as functional programming. Object-oriented programming is based on real-time objects and classes. Kotlin additionally supports pillars of OOP language like encapsulation, inheritance, and polymorphism.

Kotlin supports both functional and object-oriented programming.

Kotlin supports highlights, for example, higher-order functions, function types, and lambdas which settles on it an incredible decision for working in functional programming style. You will learn about these concepts in later chapters. This tutorial will focus on the object-oriented style of programming in Kotlin.


Object-oriented Programming (OOP)

In object-oriented style of programming, you can divide a complex issue into smaller sets by creating objects.

These objects share two characteristics:

  • state
  • behavior

Let’s take few examples:

  1. Lamp is an object
  • It can be in on or off state.
  • You can turn on and turn off lamp (behavior).


2. Bicycle is an object

  • It has current gear, two wheels, number of gear, etc. states.
  • It has braking, accelerating, changing gears, etc. behavior.

Recommended reading: What is an object?


Kotlin Class

Before you create objects in Kotlin, you need to characterize a class.

A class is a blueprint for the object.

We can consider the class a sketch (prototype) of a house. It contains every one of the insights concerning the floors, entryways, windows, and so forth In light of these descriptions, we construct the house. House is the object.

Since, numerous houses can be produced using a similar description, we can create numerous objects from a class.


How to define a class in Kotlin?

To define a class in Kotlin, class keyword is used:

class ClassName {
    // property
    // member function
    ... .. ...
}

Here’s an example:

class Lamp {

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }
}

Here, we characterized a class named Lamp.

The class has one property isOn (characterized in same route as variable), and two part works turnOn() and turnOff().

Recommended Reading: Kotlin functions

In Kotlin, either the property should be instated or should be pronounced abstract (Visit: Kotlin Abstract Class to learn more). In the above example, isOn property is instated to false.


Classes, objects, properties, part work and so on can have perceivability modifiers. For instance, the isOn property is private. This implies, the isOn property can be changed from just inside the Lamp class.

Other visibility modifiers are:

  • private – visible (can be accessed) from inside the class only.
  • public – visible everywhere.
  • protected – visible to the class and its subclass.
  • internal – any client inside the module can access them.

In the event that you don’t determine the perceivability modifier, it will be public by default.

In the above program, turnOn() and turnOff() part works are public though, isOn property is private.


Kotlin Objects

At the point when class is characterized, just the specification for the object is characterized; no memory or storage is distributed.

To access members characterized inside the class, you need to create objects. Let’s create objects of Lamp class.

class Lamp {

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }
}

fun main(args: Array<String>) {

    val l1 = Lamp() // create l1 object of Lamp class
    val l2 = Lamp() // create l2 object of Lamp class
}

This program creates two objects l1 and l2 of class Lamp. The isOn property for the two lamps l1 and l2 will be false.


How to access members?

You can access properties and member functions of a class by using . notation. For instance,

l1.turnOn()

This statement calls turnOn() work for l1 object.

Let’s take another example:

l2.isOn = true

Here, we attempted to appoint consistent with isOn property of l2 object. Note that, isOn property is private, and in the event that you attempt to access to isOn from outside the class, an exception is thrown.


Example: Kotlin Class and Object

class Lamp {

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }

    fun displayLightStatus(lamp: String) {
        if (isOn == true)
            println("$lamp lamp is on.")
        else
            println("$lamp lamp is off.")
    }
}

fun main(args: Array<String>) {

    val l1 = Lamp() // create l1 object of Lamp class
    val l2 = Lamp() // create l2 object of Lamp class

    l1.turnOn()
    l2.turnOff()

    l1.displayLightStatus("l1")
    l2.displayLightStatus("l2")
}

At the point when you run the program, the output will be:

l1 Lamp is on.
l2 Lamp is off.

In the above program,

  • Lamp class is created.
  • The class has a property isOn and three member functions turnOn(), turnOff() and displayLightStatus().
  • Two objects l1 and l2 of the Lamp class are created in the main() function.
  • Here, turnOn() function is called using l1 object: l1.turnOn(). This method sets isOn instance variable of l1 object to true.
  • And, turnOff() function is called using l2 object: l1.turnOff(). This method sets isOff instance variable of l2 object to false.
  • Then, the displayLightStatus() function is called for l1 and l2 objects which prints appropriate messages depending on whether the isOn property is true or false.

Notice that, the isOn property is introduced to false inside the class. At the point when an object of the class is created, isOn property for the object is introduced to false consequently. Thus, it’s excessive for the l2 object to call turnOff() to set isOn property to bogus.

For instance:

class Lamp {

    // property (data member)
    private var isOn: Boolean = false

    // member function
    fun turnOn() {
        isOn = true
    }

    // member function
    fun turnOff() {
        isOn = false
    }

    fun displayLightStatus() {
        if (isOn == true)
            println("lamp is on.")
        else
            println("lamp is off.")
    }
}

fun main(args: Array<String>) {

    val lamp = Lamp()
    lamp.displayLightStatus()
}

At the point when you run the program, the output will be:

lamp is off.

This tutorial is just an introduction to object-oriented programming in Kotlin. Check these chapters in sequence to learn more:

  • Kotlin Constructors and Initializers
  • Kotlin this Keyword
  • Kotlin Nested Class

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.