Unlocking the Power of Object-Oriented Programming in Kotlin

Divide and Conquer: The Core of OOP

In object-oriented programming (OOP), complex problems are broken down into smaller, manageable sets by creating objects. These objects possess two essential characteristics: state and behavior. Let’s explore this concept through everyday examples:

  • A lamp is an object with a state (on or off) and behavior (turning on and off).
  • A bicycle is an object with states (current gear, number of gears, etc.) and behaviors (braking, accelerating, changing gears, etc.).

Defining Classes in Kotlin

Before creating objects, you need to define a class, which serves as a blueprint for the object. A class is like a sketch of a house, containing details about the floors, doors, and windows. Based on this description, you can build multiple houses, just like creating multiple objects from a single class.

To define a class in Kotlin, use the class keyword. Here’s an example:

class Lamp {
    private var isOn = false
    fun turnOn() { isOn = true }
    fun turnOff() { isOn = false }
}

Visibility Modifiers: Controlling Access

In Kotlin, classes, objects, properties, and member functions can have visibility modifiers, which control access to these elements. There are five visibility modifiers:

  • private: Accessible only within the class.
  • public: Accessible everywhere.
  • protected: Accessible to the class and its subclasses.
  • internal: Accessible to clients within the module.

If you don’t specify a visibility modifier, it defaults to public.

Creating Objects and Accessing Members

When a class is defined, no memory is allocated. To access members, you need to create objects. Let’s create two objects, l1 and l2, of the Lamp class:

val l1 = Lamp()
val l2 = Lamp()

To access properties and member functions, use the dot notation. For example:

l1.turnOn()

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

Example: Kotlin Class and Objects

Let’s create a Lamp class with a property isOn and three member functions: turnOn(), turnOff(), and displayLightStatus(). We’ll then create two objects, l1 and l2, and demonstrate how to access members:

class Lamp {
    private var isOn = false
    fun turnOn() { isOn = true }
    fun turnOff() { isOn = false }
    fun displayLightStatus() {
        if (isOn) println("The light is on")
        else println("The light is off")
    }
}

fun main() {
    val l1 = Lamp()
    val l2 = Lamp()

    l1.turnOn()
    l2.turnOff()

    l1.displayLightStatus()
    l2.displayLightStatus()
}

When you run the program, the output will be:

The light is on
The light is off

To learn more, explore the following chapters:

Leave a Reply