Encapsulation is union data and logic to one unit and hide data from external access. As a result, we have reducing couplings between software components and have more readable and stable code.

Following access modifiers can be applied

  • private - name is accessible only within class, where it was declared
  • protected - name is accessible only within class and its subclasses
  • internal - name is accessible for everyone within same module
  • public - the name is accessible 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) { ... }