Kotlin Visibility Modifiers: public, private, protected, internal

Kotlin course · Object-oriented programming · Lesson 36 of 51

Visibility modifiers control who can see and use a class, function or property. Hiding the details of a class (called encapsulation) lets you change how it works later without breaking the code that uses it.

The four modifiers

ModifierClass member is visible…Top-level declaration is visible…
public (default)everywhereeverywhere
privateinside the class onlyinside the same file only
protectedinside the class and its subclassesnot allowed
internalinside the same moduleinside the same module

If you don’t write a modifier, it’s public.

private: hide the details

class Wallet {
    private var balance = 0

    fun add(amount: Int) {
        if (amount > 0) balance += amount
    }

    fun show() = "Balance: ₹$balance"
}

fun main() {
    val w = Wallet()
    w.add(500)
    w.add(-100)          // ignored by the class's own rule
    println(w.show())
    // w.balance = 1_000_000   // ❌ doesn't compile: balance is private
}

Output:

Balance: ₹500

Because balance is private, the only way to change it is through add, which enforces the rule.

Public getter, private setter

Often you want others to read a property but not change it:

class Counter {
    var count = 0
        private set

    fun increment() { count++ }
}

fun main() {
    val c = Counter()
    c.increment()
    c.increment()
    println(c.count)
    // c.count = 99   // ❌ the setter is private
}

Output:

2

protected: for subclasses

protected members are hidden from outside code, but child classes can use them:

open class Vehicle {
    protected var fuel = 40

    fun fuelLeft() = "$fuel litres left"
}

class Car : Vehicle() {
    fun drive(km: Int) {
        fuel -= km / 15      // OK: Car is a subclass
    }
}

fun main() {
    val car = Car()
    car.drive(150)
    println(car.fuelLeft())
    // car.fuel   // ❌ protected: not visible here
}

Output:

30 litres left

internal: inside one module

A module is a set of Kotlin files compiled together, such as one Gradle module in an Android project (app, core, data…). internal code can be used anywhere in that module, but not by other modules:

// in the :data module
internal class ApiClient { /* … */ }      // only the data module can use this

class UserRepository {                   // public: other modules can use this
    private val api = ApiClient()
}

internal is useful for libraries and multi-module apps, to keep helper classes from leaking into the public API.

private at the top level

A private function or property at the top of a file can only be used in that file:

// Utils.kt
private fun formatInternal(x: Int) = "#$x"     // only Utils.kt can call this
fun format(x: Int) = formatInternal(x)         // public

Visibility of constructors

class Token private constructor(val value: String) {
    companion object {
        fun create() = Token(List(8) { ('a'..'z').random() }.joinToString(""))
    }
}

fun main() {
    val t = Token.create()
    println(t.value.length)
    // Token("abc")   // ❌ the constructor is private
}

Output:

8

Overrides keep or widen visibility

When you override a protected member, it stays protected unless you make it public. You can’t make an override less visible than the original.

Which modifier should I use?

  1. Start with private for everything inside a class.
  2. Make it public only when other code needs it.
  3. Use protected only for members that subclasses must use.
  4. Use internal for code shared across files in one module but not meant for other modules.

Common mistakes

  • Making every property public var: anyone can then put the object in an invalid state. Use private set or private.
  • Using protected at the top level: it’s only allowed inside classes.
  • Expecting internal to mean “same package”: it means the same module.

Exercise

Create a Student class where the marks list can be read from outside as a read-only List, but marks can only be added through a function that checks they’re between 0 and 100.

class Student(val name: String) {
    private val _marks = mutableListOf<Int>()
    val marks: List<Int> get() = _marks

    fun addMark(mark: Int): Boolean {
        if (mark !in 0..100) return false
        _marks.add(mark)
        return true
    }

    val average: Double get() = if (_marks.isEmpty()) 0.0 else _marks.average()
}

fun main() {
    val s = Student("Meera")
    println(s.addMark(85))
    println(s.addMark(120))
    println(s.addMark(92))
    println("${s.name}: ${s.marks}, average ${s.average}")
}

Output:

true
false
true
Meera: [85, 92], average 88.5

This “private mutable, public read-only” pattern (_marks and marks) is used everywhere in Android ViewModels.

FAQ

What is the default visibility in Kotlin?

public. Unlike Java, there’s no package-private default.

What is the difference between private and protected in Kotlin?

private members are visible only inside the class. protected members are also visible in subclasses.

What does internal mean in Kotlin?

Visible everywhere inside the same module (for example, one Gradle module), and hidden from other modules.

WhatsApp us📞 Call now