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.
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
private – Visible only inside the same class.protected – Visible in the class and its subclasses.internal – Visible within the same module.public – Visible everywhere (default modifier).
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.
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")
}
private? internal members.internal members of other modules, even if they are in the same project.private variables and public functions for controlled access.