类,对象,接口,构造函数,方法,属性以及属性的setter方法都可以用可见修饰符(visibility modifiers)来做修饰(getter同属性有着相同的可见性)。
在Kotlin中有以下四个可见性修饰符
Ø private:同一类或文件(针对包级别定义)中可见
Ø protected:同private 加子类可见
Ø internal:在同一个模块中可见(如果声明范围的所有者是可见的)
Ø public:公共,所有都可见
Packages
函数、属性、类、对象及接口,都可以在顶层(top-level)定义;即直接定义在包内。
// file name:example.kt package foo
fun baz() {} class Bar {} |
l 没有显式定义访问修饰符,默认为“public
”,对所有可见。
l 使用“private”,该文件可见。
l 使用“internal”,该模块可见。
l 不能使用“protected
”修饰。
// 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 |
Classes and Interfaces
在类或接口中使用:
Ø private:只该类可见(包括该类的所有成员)
Ø protected:同private 加子类可见
Ø internal:在同一个模块中可见
Ø public:公共,所有都可见
注:在Kotlin中,外层的类( outer class)不能访问内部类(inner classes)的private成员。
重写了一个“protected
”成员,若没有再显式声明,默认为“protected
”。
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 } |
构造函数(Constructors)
可以在类的主构造函数前添加可见修饰符,来指定可见性(构造函数需要使用“constructor ”关键字显式声明)。
默认情况下,所有的构造函数都是“public”。
classC private constructor(a: Int) { ... } |