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
?
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) {
}