0

My code -

fun main() {
    val student = Student()
    student.greet()
}

open class Person(open var name: String) {
    fun greet() {
        println("Hello $name")
    }
}

class Student(override var name: String = "John Doe"): Person(name) {

}

Here I have a parent class Person and a child class Student. parent class Person has property name and method greet(). child class Student is inheriting them.


Here I am able to directly modify name variable of Student class from main() function using student.name. I want to encapsulate name variable to prevent name from being directly modified from main() function so that the constructor Student() is the only way to set the value of name variable.


Usually private visibility modifier keyword is used to encapsulate variables in a class. But apparently when the variables have open or override modifier, this technique does not work.


So, is it possible to encapsulate name variable?

Payel Senapati
  • 1,134
  • 1
  • 11
  • 27
  • 1
    Remove open var and var – P.Juni Aug 09 '20 at 09:25
  • 1
    you can use both solutions from this qustion to make `name` unmodifiable from outside the class https://stackoverflow.com/questions/56351124/kotlin-data-class-private-setter-public-getter – IR42 Aug 09 '20 at 10:54

1 Answers1

1

Remove the open keyword, and call the Person's constructor to set it instead of overriding it from Student (which is also null-prone at the init block of Person, see here):

open class Person(private var _name: String) {
    val name get() = _name

    fun greet() {
        println("Hello $name")
    }
}

class Student(name: String = "John Doe"): Person(name) {

}
Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49
  • Here I am getting error in `student.greet()` in `main()` `function`. Error --> Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public final fun greet(): Unit defined in sampleInheritance.Student – Payel Senapati Aug 09 '20 at 09:43
  • you cannot use inheritance without `open`, classes are final by default – IR42 Aug 09 '20 at 10:00
  • that's my question, is it possible to implement both inheritance and encapsulation together? – Payel Senapati Aug 09 '20 at 10:01
  • @IR42 in that case `name` `variable` can be modified directly from `main()` `function` using `student.name`. I cannot achieve `encapsulation`. But `encapsulation` is always desired in any programming – Payel Senapati Aug 09 '20 at 10:05
  • @PayelSenapati Ah I actually misunderstood the problem at first. I've updated it. This will delegate getter function of `name` to return the `_name`. – Animesh Sahu Aug 09 '20 at 12:36