Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Encapsulation and Visibility Modifiers | Object-Oriented Concepts in Kotlin
Kotlin Classes and Objects

bookEncapsulation and Visibility Modifiers

Свайпніть щоб показати меню

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?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 1

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 3. Розділ 1
some-alt