Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 134 ยท Classes and Objects

Visibility Modifiers

Learn Kotlin visibility modifiers: public by default, private, protected and internal, top-level and file-private declarations, restricted setters and the exposure rules, with runnable examples.

Good code hides what callers should not touch. A bank account lets you deposit money but not overwrite the balance; a library exposes a few functions and keeps a hundred helpers private so it can change them later without breaking anyone. Visibility modifiers are how you draw that line, and the compiler enforces it.

Kotlin has four of them: public, private, protected and internal. The default is public, which is different from Java's package-private. In this lesson you learn what each one means for class members and for top-level declarations, how to restrict only a setter, why the compiler refuses to expose a hidden type through a public signature, and which modifier to choose in practice.

The four modifiers at a glance

Modifier Visible to Applies to
public (default) everyone, everywhere top level and members
internal everything in the same module top level and members
protected the class itself and its subclasses members only
private the class (or the file, at top level) top level and members

A module is a unit that is compiled together: one Gradle or Maven project, or one IntelliJ module. In the one-file programs on this site the whole file is one module, so internal looks the same as public here; its effect shows in real projects with several modules (more in Project Structure and Modules).

private members

A private member can be used only inside the class that declares it. This is the tool for protecting state:

Kotlin Private state behind a public API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The wallet prints 13.25. Outside code can only reach deposit and balance, so the invariant "the balance is only changed by a positive deposit" is guaranteed by the class itself. Now try to break the rules:

Kotlin Touching a private member (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This does not compile: main.kt:7:7: error: cannot access 'var cents: Int': it is private in 'Wallet'. Unlike Java, a Kotlin outer class cannot see the private members of its nested classes (a nested class can use the private members of its outer class through an instance, but not the other way round). The simple rule: private means "inside this class's own braces", and a nested class counts as being inside its outer class.

protected members

protected is like private but also allows subclasses. It is available only for members, never for top-level declarations:

Kotlin protected members and subclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is square: side 4 and blob: no details. Outside the hierarchy nobody can call describeDetails(). Notice that the override in Square keeps the protected visibility, because an override inherits the visibility of the member it overrides unless you write a different modifier (you may widen it, never narrow it). Inheritance itself is covered in Inheritance.

Unlike Java, protected in Kotlin does not grant package access: only the class and its subclasses see the member.

Top-level declarations

Functions, properties and classes outside any class can be private too. For a top-level declaration, private means visible inside the same file, which is ideal for helpers:

Kotlin File-private helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Other files in a real project cannot call decorate or read GREETING, so you are free to rename or delete them. Kotlin projects lean on this: instead of one class per file with private methods, a file often holds several related top-level functions with a few public entry points and many private helpers.

Top-level internal declarations are visible across the whole module but not to other modules, which is the right default for the implementation details of a library.

Restricting a setter

Visibility can differ between a property and its accessors. A very common pattern: public getter, private setter.

Kotlin Public getter, private setter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints 60 and then 100 true. Callers read progress, but only advance can change it, so it can never be negative or above 100. The setter can be private, protected or internal, but it can never be more visible than the property.

Private constructors

The constructor has a visibility too. Make it private to force callers through factory functions or a singleton:

Kotlin
class Registry private constructor() {
    companion object {
        val instance = Registry()
    }
}

This read-only snippet shows the syntax: the constructor keyword is required as soon as the constructor has a modifier. See Constructors for a complete runnable example.

The exposure rule

A public function may not mention a less visible type in its signature. Otherwise a caller could receive an object whose type it is not allowed to name:

Kotlin Exposing a private type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler rejects it with main.kt:3:5: error: 'public' function exposes its 'private-in-file' return type 'Secret'. The same applies to parameter types, supertypes and property types. You fix it by making the function private as well, or by making the class more visible.

The rule has a useful consequence: you can change a private class's name, fields and constructor at will, knowing that no signature that others compile against mentions it.

Visibility is not security

Visibility is a compile-time design tool, not a security boundary. On the JVM, reflection and Java code can read private fields at run time. Never rely on private to hide secrets such as passwords; treat it as a way to prevent accidental misuse and to keep your options open for later changes.

Choosing a modifier

  1. Start with private. Hide everything that callers do not need. You can always widen later; narrowing breaks callers.
  2. Use internal for module-wide helpers that are not part of your published library API.
  3. Use protected rarely. It exposes subclass contracts, and composition (see Delegation) is often a better design than a protected hook.
  4. Keep public for the actual API, and think of each public member as a promise.
  5. Prefer a restricted setter over a public var, so the class owns the rules for its own state.

A popular library rule: public by default is dangerous only if you forget to review it. Kotlin offers an explicit API mode compiler option that requires you to write public and return types for public declarations, which makes accidental exposure harder. It is a Gradle setting, so it is not available in this runner.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the default visibility of a declaration in Kotlin?

    Kotlin declarations are public unless you write another modifier. There is no package-private visibility.
  2. 2. What does private mean for a top-level function?

    For top-level declarations private restricts visibility to the containing file.
  3. 3. Which declaration lets everybody read balance but only the class change it?

    A restricted setter keeps the getter public while only the class can assign the property.
  4. 4. A public function returns an instance of a private class. What happens?

    Kotlin refuses to expose a type in a signature that callers could not name, so you must narrow the function or widen the class.
  5. 5. Who can see a protected member?

    Kotlin's protected grants access to subclasses only. Unlike Java, it does not include the package.

Summary

  • Kotlin has public (default), internal (same module), protected (class and subclasses) and private (class, or file at top level).
  • Top-level private hides helpers inside a file; internal hides implementation details from other modules.
  • A property may have a more restricted setter: var x = 0 followed by private set.
  • A declaration cannot expose a type that is less visible than itself; the compiler checks this.
  • Visibility prevents accidental misuse at compile time but is not a security feature.
  • Start with private and widen only when needed.

Next: Inheritance