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 elements have three visibility modifiers:

  • public (default): Visible everywhere

  • private: Visible inside the same file only

  • internal: Visible inside this module

Module vs. package

Note that a module is not the same as a package. In Kotlin, a module is defined as a set of Kotlin sources that are compiled together. This might mean:

  • A Gradle source set

  • A Maven project

  • An IntelliJ IDEA module

  • A set of files compiled with one invocation of an Ant task

Code examples

Let’s see some examples, starting with the default visibility, which makes elements visible everywhere and can be explicitly specified using the public modifier.

Default visibility (public)

To ensure the correct execution of this code, follow these steps:

  1. Copy the main() function from the Main.txt file and paste it into File1.kt. Then, click the “Run” button to view the expected output.

  2. After step 1, remove the copied code from the Main.txt file in File1.kt. Paste this code into File2.kt and click the “Run” button to see the expected output.

Points to remember:

  • If the main() function is present in both File1.kt and File2.kt, the code will not work as intended, resulting in errors.

  • Also, errors will occur if no main() function is defined in either File1.kt or File2.kt as instructed in steps 1 and 2.

Get hands-on with 1200+ tech skills courses.