Visibility Modifiers in Kotlin

Visibility modifiers in Kotlin determine the accessibility of classes, objects, interfaces, constructors, functions, and properties. They control which parts of code can access a particular declaration, helping enforce encapsulation and clean architecture.

1. Why Visibility Modifiers Matter

2. Types of Visibility Modifiers

3. How Visibility Modifiers Work

Let’s see examples of each modifier in a Kotlin class:


class Airplane(private val name: String, internal var maxAltitude: Int) {

    private fun checkSystems() {
        println("Checking all systems for $name")
    }

    protected fun takeOff() {
        println("$name is taking off")
    }

    internal fun refuel() {
        println("$name is refueling")
    }

    fun status() {
        println("Airplane $name, max altitude $maxAltitude")
        checkSystems()  // private function accessible inside class
    }
}

class Jet : Airplane("JetOne", 40000) {
    fun jetTakeOff() {
        takeOff()  // protected function accessible in subclass
        // checkSystems()  -> Not accessible, private in parent class
        refuel()    // internal function accessible in same module
    }
}

fun main() {
    val plane = Airplane("Boeing", 35000)
    plane.status()     // Accessible
    // plane.checkSystems()  -> Not accessible, private
    // plane.takeOff()      -> Not accessible, protected
    plane.refuel()     // Accessible if in same module
}
  

3.1 Notes on Each Modifier

4. Practical Use Cases

5. Technical Interview Questions

6. Key Takeaways