Encapsulation in Kotlin

Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP). It means bundling data (variables) and methods (functions) that operate on that data within a single unit — a class. In Kotlin, encapsulation is achieved mainly using access modifiers such as private, protected, and public, which control visibility and safeguard the internal state of objects.

1. Why Encapsulation Matters

2. What is Encapsulation?

Encapsulation hides the internal implementation details of a class and exposes only what’s necessary through public interfaces. This is often referred to as the “black box” concept — you can use the class without knowing how it works inside.


class BankAccount {
    private var balance: Double = 0.0   // Hidden from outside

    fun deposit(amount: Double) {
        if (amount > 0) balance += amount
    }

    fun withdraw(amount: Double) {
        if (amount <= balance) balance -= amount
        else println("Insufficient balance")
    }

    fun getBalance(): Double = balance  // Controlled access
}

fun main() {
    val account = BankAccount()
    account.deposit(500.0)
    account.withdraw(100.0)
    println("Current Balance: ${account.getBalance()}")
}
  

Output:


Current Balance: 400.0
  

3. How Encapsulation Works in Kotlin

3.1 Example: Custom Getters and Setters


class Pilot {
    var name: String = "Unknown"
        private set  // Restrict modification from outside

    var experienceYears: Int = 0
        set(value) {
            if (value >= 0) field = value
            else println("Experience cannot be negative!")
        }

    fun assignName(newName: String) {
        if (newName.isNotBlank()) name = newName
    }
}

fun main() {
    val pilot = Pilot()
    pilot.assignName("Amelia Earhart")
    pilot.experienceYears = 5
    println("${pilot.name} has ${pilot.experienceYears} years of experience.")
}
  

Output:


Amelia Earhart has 5 years of experience.
  

4. How to Implement Encapsulation Manually (without Kotlin’s property syntax)

You can also implement encapsulation manually using private variables and explicit getter/setter functions, similar to Java-style:


class Airplane {
    private var altitude: Int = 0

    fun setAltitude(value: Int) {
        if (value >= 0) altitude = value
    }

    fun getAltitude(): Int {
        return altitude
    }
}

fun main() {
    val plane = Airplane()
    plane.setAltitude(3000)
    println("Current altitude: ${plane.getAltitude()} ft")
}
  

5. Technical Interview Questions

6. Key Takeaways