Sobes.tech
Junior

Kuidas toimub inkapsulatsioon Kotlinis?

sobes.tech AI

Vastus AI-lt

Encapsulation in Kotlin is achieved through access modifiers and properties.

Access modifiers:

  • public: accessible from anywhere (default).
  • internal: accessible within the same module.
  • protected: accessible in its class and subclasses.
  • private: accessible only within the class where it is declared.

Properties are used to manage access to class data. They can have a getter and setter, which can be overridden to add logic during reading or writing the value.

class Person {
    // Private field, accessible only within the class
    private var _name: String = ""

    // Property with public getter and private setter
    var name: String
        get() = _name
        private set(value) {
            _name = value
        }

    // Public function to set the name, controlling input
    fun setName(newName: String) {
        if (newName.isNotBlank()) {
            name = newName
        } else {
            println("Name cannot be blank")
        }
    }
}

fun main() {
    val person = Person()
    person.setName("Alice") // Using the controlled method to change
    println(person.name)    // Reading the value via getter
    // person.name = "Bob"   // Compilation error, setter is private
}