在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) {
}
这里我有一个parent
class
Person
和一个child
class
Student
。 parent
class
Person
有 property
name
和 method
greet()
。 child
class
Student
是 inheriting
他们
这里我可以直接修改 name
variable
of Student
class
from main()
function
using student.name
.我想 encapsulate
name
variable
以防止 name
从 main()
function
直接修改,以便 constructor
Student()
是设置 name
variable
.
值的唯一方法
通常private
visibility modifier
keyword
在class
中习惯encapsulate
variables
。
但显然当 variables
有 open
或 override
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) {
}
我的代码-
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) {
}
这里我有一个parent
class
Person
和一个child
class
Student
。 parent
class
Person
有 property
name
和 method
greet()
。 child
class
Student
是 inheriting
他们
这里我可以直接修改 name
variable
of Student
class
from main()
function
using student.name
.我想 encapsulate
name
variable
以防止 name
从 main()
function
直接修改,以便 constructor
Student()
是设置 name
variable
.
通常private
visibility modifier
keyword
在class
中习惯encapsulate
variables
。
但显然当 variables
有 open
或 override
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) {
}