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

bookEncapsulation and Visibility Modifiers

Scorri per mostrare il menu

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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 3. Capitolo 1
some-alt