- 子类对protected函数的访问规则:
- 在Kotlin中,
protected
修饰的成员函数对子类是可见的。也就是说,子类可以直接调用父类中定义的protected
函数。
- 不同包结构下的访问情况:
- 无论子类与父类是否在同一个包中,子类都能访问父类的
protected
函数。protected
修饰符的作用范围不仅局限于包,更侧重于类的继承体系。即使子类在不同包中,只要继承自包含protected
函数的父类,就可以访问该函数。
- 子类重写protected函数后的可见性限制和要求:
- 重写后的函数可见性不能比被重写函数的可见性更严格。由于父类函数是
protected
,子类重写后的函数可见性可以是protected
或者internal
(internal
表示模块内可见,在同一个模块中,它的访问范围比protected
更广,但不会违反“不能比被重写函数可见性更严格”的规则),但不能是private
(private
表示仅在类内部可见,比protected
更严格)。如果不指定可见性修饰符,默认的可见性为public
,这也是符合要求的,因为public
比protected
更宽松。例如:
open class Parent {
protected open fun protectedFunction() {
println("This is a protected function in Parent")
}
}
class Child : Parent() {
// 正确,可见性为protected
override protected fun protectedFunction() {
println("This is a overridden protected function in Child")
}
// 正确,可见性为internal
override internal fun protectedFunction() {
println("This is a overridden internal function in Child")
}
// 正确,默认可见性为public
override fun protectedFunction() {
println("This is a overridden public function in Child")
}
// 错误,private比protected更严格
// override private fun protectedFunction() {
// println("This is a overridden private function in Child")
// }
}