Search⌘ K
AI Features

Visibility Modifiers

Explore Kotlin visibility modifiers including public, private, protected, and internal to understand how to restrict or allow access to class elements. Discover how these modifiers affect inheritance and module visibility to help you design secure and maintainable code in Kotlin applications.

Introduction to visibility

When we design our classes, we prefer to expose as little as possible. If there is no reason for an element to be visible, we prefer to keep it hidden.

Visibility defines where an element can be used. If an element is not visible, it cannot be used.

This is why if there is no good reason to have a less restrictive visibility type, it is good practice to make the visibility of classes and elements as restrictive as possible. We do this using visibility modifiers.

Visibility modifiers for class members

For class members, these are the four visibility modifiers we can use:

  • public (default): Visible everywhere for anyone who can see the declaring class

  • private: Visible inside this class only

  • protected: Visible inside this class and in subclasses

  • internal: Visible inside this module for anyone who can see the declaring class

Visibility modifiers for top-level elements

Top-level ...