可见性修饰
Kotlin有四种可见性修饰符:private, protected, internal, public
用法见下面表格:
修饰符 | 顶级(声明在package底下) | 类级(声明在一个类里) |
---|---|---|
private | 当前文件可见 | 只当前类可见 |
protected | (不可直接在包下使用此声明) | 当前类及其子类可见 |
internal | 当前module可见 | 当前module可见 |
public | 随处可见 | 随处可见 |
值得注意的是,如果不做修饰,默认则是public
例子:
- 顶级
// file name: example.kt
package foo
private fun foo() {} // visible inside example.kt
public var bar: Int = 5 // property is visible everywhere
private set // setter is visible only in example.kt
internal val baz = 6 // visible inside the same module
- 类级
open class Outer {
private val a = 1
protected open val b = 2
internal val c = 3
val d = 4 // public by default
protected class Nested {
public val e: Int = 5
}
}
class Subclass : Outer() {
// a is not visible
// b, c and d are visible
// Nested and e are visible
override val b = 5 // 'b' is protected
}
class Unrelated(o: Outer) {
// o.a, o.b are not visible
// o.c and o.d are visible (same module)
// Outer.Nested is not visible, and Nested::e is not visible either
}
可继承声明
继承修饰符open(与java的final相对),使用Kotlin声明一个可以被继承的类必须冠以open
网友评论