📜  Kotlin可见性修改器

📅  最后修改于: 2020-10-05 15:01:33             🧑  作者: Mango

在本文中,您将了解Kotlin中的所有4种可见性修改器,以及它们在不同情况下的工作方式。

可见性修饰符是用于设置类,对象,接口,构造函数,函数,属性及其设置器的可见性(可访问性)的关键字。 (您不能设置吸气剂的可见性修改器,因为它们始终具有与属性相同的可见性。)

在Kotlin类和对象文章中,您简要了解了publicprivate可见性修饰符。您将详细了解另外两个protected可见性修饰符,这些修饰符是protectedinternal (以及publicprivate )。


封装内的可见性修改器

程序包组织了一组相关的函数,属性和类,对象和接口。 推荐阅读: Kotlin包装

Modifier Description
public declarations are visible everywhere
private visible inside the file containing the declaration
internal visible inside the same module (a set of Kotlin files compiled together)
protected not available for packages (used for subclasses)

注意:如果未指定可见性修改器,则默认情况下它是public的。

让我们举个例子:

// file name: hello.kt

package test

fun function1() {}   // public by default and visible everywhere

private fun function2() {}   // visible inside hello.kt

internal fun function3() {}   // visible inside the same module

var name = "Foo"   // visible everywhere
    get() = field   // visible inside hello.kt (same as its property)
    private set(value) {   // visible inside hello.kt
        field = value
    }

private class class1 {}   // visible inside hello.kt

类和接口内部的可见性修改器

这是可见性修饰符对在类内声明的成员(函数,属性)的工作方式:

Modifier Description
public visible to any client who can see the declaring class
private visible inside the class only
protected visible inside the class and its subclasses
internal visible to any client inside the module that can see the declaring class

注意:如果您在派生类中重写protected 成员而未指定其可见性,则其可见性也将protected

让我们举个例子:

open class Base() {
    var a = 1                 // public by default
    private var b = 2         // private to Base class
    protected open val c = 3  // visible to the Base and the Derived class
    internal val d = 4        // visible inside the same module

    protected fun e() { }     // visible to the Base and the Derived class
}

class Derived: Base() {

    // a, c, d, and e() of the Base class are visible
    // b is not visible

    override val c = 9        // c is protected
}

fun main(args: Array) {
    val base = Base()

    // base.a and base.d are visible
    // base.b, base.c and base.e() are not visible

    val derived = Derived()
    // derived.c is not visible
}

更改构造函数的可见性

默认情况下,构造函数的可见性是public 。但是,您可以更改它。为此,您需要显式添加constructor关键字。

在以下示例中,默认情况下,构造函数是public的:

class Test(val a: Int) {
    // code
}

您可以通过以下方法更改其可见性。

class Test private constructor(val a: Int) {
    // code
}

这里的构造函数是private


注意:在Kotlin中,局部函数,变量和类不能具有可见性修饰符。