Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Encapsulation and Visibility Modifiers | Object-Oriented Concepts in Kotlin
Kotlin Classes and Objects

bookEncapsulation and Visibility Modifiers

Pyyhkäise näyttääksesi valikon

What is Encapsulation?

Encapsulation is a core concept in object-oriented programming that helps you protect the internal state of your classes. By keeping some properties and methods hidden from outside code, you can control how your data is accessed and modified. Encapsulation allows you to expose only what is necessary and hide implementation details, making your code safer and easier to maintain.

Visibility Modifiers in Kotlin

Visibility modifiers in Kotlin let you specify which parts of your code can access certain properties, methods, or classes. The most common visibility modifiers are:

  • public: accessible everywhere;
  • private: accessible only within the class or file where it is declared;
  • protected: accessible within the class and its subclasses;
  • internal: accessible within the same module.

By using these modifiers, you can enforce encapsulation and prevent unwanted access to sensitive data.

SecretBox.kt

SecretBox.kt

copy

The SecretBox example demonstrates how visibility modifiers control access to class members. The secret property is marked as private, so it cannot be accessed directly from outside the SecretBox class. Only the class's own methods can read or modify it. The isLocked property is public by default, meaning you can access and change it from anywhere. By carefully choosing visibility modifiers, you can ensure that only trusted code can interact with sensitive data, while still providing safe ways to work with your class.

question mark

Which visibility modifier makes a property accessible only within its class?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 1

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 3. Luku 1
some-alt