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

bookEncapsulation and Visibility Modifiers

Svep för att visa menyn

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 1
some-alt