在Kotlin实现继承的同时,是否可以封装open和override变量来防止main()函数直接访问?

Is it possible to encapsulate open and override variables to prevent direct access from main() function while implementing inheritance in Kotlin?

我的代码-

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

}

这里我有一个parentclassPerson和一个childclassStudentparent class Personproperty namemethod greet()child class Studentinheriting 他们


这里我可以直接修改 name variable of Student class from main() function using student.name .我想 encapsulate name variable 以防止 namemain() function 直接修改,以便 constructor Student() 是设置 name variable.

值的唯一方法

通常privatevisibility modifierkeywordclass中习惯encapsulatevariables。 但显然当 variablesopenoverride modifier 时,这种技术不起作用。


那么,是否可以encapsulate name variable

删除open关键字,并调用Person的构造函数来设置它而不是从Student覆盖它(这也是null-prone在Person的init块,参见 ):

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

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

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

}