首页 Kotlin学习笔记(7) - 可见修饰符
文章
取消

Kotlin学习笔记(7) - 可见修饰符

一、修饰符

Kotlin中有四种可见修饰符,可为类、对象、接口、构造函数、方法、属性及属性的访问器添加可见修饰符

  • private:当前文件可见
  • protected:与private类似,但它在子类中也是可见的。不适用于顶层声明,如顶层类、顶层属性、顶层方法等
  • internal:当前模块可见
  • public: 默认值,任何位置可见

二、修饰符覆盖

如果去覆盖一个protectedinternal成员,并且没有显式的指定可见性,则它仍然具有原始成员的可见性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
open class Outer {
    private val a = 1
    protected open val b = 2
    internal open 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
    override val c = 7   // 'c' is internal
}

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
}

三、构造函数可见性

类指定构造函数可见性时需要明确指定constructor关键字

1
class C private constructor(a: Int) { ... }
本文由作者按照 CC BY 4.0 进行授权

Kotlin学习笔记(6) - 接口

Kotlin学习笔记(8) - 扩展