English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Classes and Objects

In this article, I will introduce object-oriented programming in Kotlin. You will learn what a class is, how to create an object, and how to use it in a program.

Kotlin supports both functional programming and object-oriented programming.

Kotlin supports such asHigher-Order Functions,Function Types and LambdaClassesFunctions, which makes it an ideal choice for using functional programming styles. You will learn about these concepts in the following chapters. This article will focus on the object-oriented programming style in Kotlin.

Object-Oriented Programming (OOP)

In the object-oriented programming style, complex problems can be divided into smaller sets by creating objects.

These objects have two features:

  • State

  • Behavior

Let's take a few examples:

  1. Lamp (light) is an object

    • It can be in the on (lit) or off (extinguished) state.

    • You can turn on (turn on the light) and turn off (turn off the light) (behaviors).

  2. Bicycle is an object

    • It has states such as gears, two wheels, and the number of gears.

    • It has behaviors such as braking, accelerating, and shifting gears.

You will continue to learn the detailed features of object-oriented programming, such as:Data Encapsulation,Inheritance and Polymorphism. This article will focus on the basic knowledge that makes things simple.

Kotlin Class

Before creating an object in Kotlin, you need to define a class.

A class is the blueprint of an object.

We can view a class as the blueprint (prototype) of a house. It contains all the details about the floor, doors, windows, and so on. Based on these descriptions, we build houses. Houses are objects.

Since many houses can be built with the same description, we can create many objects based on a class.

How to define a class in Kotlin?

To define a class in Kotlin, you can use the keyword class:

class ClassName {
    // Properties
    // Member Function
    ... .. ...
}

Here is an instance of it:

class Lamp {
    //Property (Data Member)
    private var isOn: Boolean = false
    // Member Function
    fun turnOn() {
        isOn = true
    }
    // Member Function
    fun turnOff() {
        isOn = false
    }
}

Here, we define a class named Lamp.

This class has a property isOn (defined in the same way as a variable) and two member functions turnOn() and turnOff().

In Kotlin, either you must initialize the property or you must declare it as abstract. In the above example, the isOn property is initialized to false.

Classes, objects, properties, member functions, and so on can have visibility modifiers. For example, the isOn property is private. This means that the isOn property can only be changed within the Lamp class.

Other visibility modifiers include:

  • private - Visible only within the class (can be accessed).

  • public - Visible everywhere.

  • protected - Visible to the class and its subclasses.

  • internal - Any client within the module can access them.

You will learn later inKotlin Visibility ModifiersLearn about the protected and internal modifiers in this article.

If no visibility modifier is specified, the default value is public by default.

In the above program, the turnOn() and turnOff() member functions are public, while the isOn property is private.

Kotlin Object

When defining a class, only the specification of the object is defined; no memory or storage space is allocated.

To access the members defined in the class, you need to create an object. Let's create an object of the 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 an object of the Lamp class l1object
    val l2 = Lamp() // Create an object of the Lamp class l2object
}

This program creates two objects l1and l2Class Lamp. The isOn two light bulb performance l1and l2will be false.

How to access members?

You can use the . symbol to access the properties and member functions of the class. For example,

l1.turnOn()

This statement calls the object l1 the turnOn() function.

Let's take another example:

l2.isOn = true

Here, we try to assign true to the object l2 Please note that the isOn property is private, and if you try to access isOn from outside the class, an exception will be 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 light is on.")
        else
            println("$lamp light is off.")
    }
}
fun main(args: Array<String>) {
    val l1 = Lamp() // Create an object of the Lamp class l1object
    val l2 = Lamp() // Create an object of the Lamp class l2object
    l1.turnOn()
    l2.turnOff()
    l1.displayLightStatus("l1)
    l2.displayLightStatus("l2)
}

When running the program, the output is:

l1 The light is on.
l2 The light is off.

In the above program:

  • The Lamp class has been created.

  • This class has one property isOn and three member functions turnOn(), turnOff(), and displayLightStatus().

  • In the main() function, two objects L1and L2.

  • Here, using l1object l1.turnOn() calls the turnOn() function. This method sets the l1the isOn instance variable of the object is set to true.

  • At the same time, using l2 object: l2.turnOff() calls the turnOff() function. This method sets the l2the isOff instance variable of the object is set to false.

  • Then, for l1and l2The object calls the displayLightStatus() function, which prints an appropriate message based on whether the isOn property is true or false.

Note that within the class, the isOn property is initialized to false. When creating an object of this class, the isOn property of the object will be automatically initialized to false. Therefore, there is no need to2 The object calls turnOff() to set the isOn property to false.

For example:

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("The light is on.")
        else
            println("The light went out.")
    }
}
fun main(args: Array<String>) {
    val lamp = Lamp()
    lamp.displayLightStatus()
}

When running the program, the output is:

The light went out.

This article is a basic introduction to object-oriented programming in Kotlin.