Encapsulation

Following visibility modifiers can be applied inside class

  • private - name visible only inside this class
  • protected - name visible only inside this class and its subclasses
  • internal - name visible for everyone inside same module
  • public - the name is visible to everyone; this is the default modifier, so you can omit it

Note that in Kotlin, outer class does not see private members of its inner classes.

Kotlin does not allow protected members inside interface and object.

Kotlin does not allow abstract private functions, only with body.

If you override a protected member and do not specify the visibility explicitly, the overriding member will also have protected visibility.

You can apply modifier to the class constructor.

open class Outer {
    private val a = 1
    protected open val b = 2
    internal val c = 3
    val d = 4  // public by default
    
    protected class Nested {
        public val e: Int = 5
    }
}

class Subclass : Outer() {
    // a is not visible
    // b, c and d are visible
    // Nested and e are visible

    override val b = 5   // 'b' is protected
}

class Unrelated(o: Outer) {
    // o.a, o.b are not visible
    // o.c and o.d are visible (same module)
    // Outer.Nested is not visible, and Nested::e is not visible either 
}

class C private constructor(a: Int) { ... }