个性化阅读
专注于IT技术分析

Kotlin可见性修改器

本文概述

可见性修饰符是关键字, 用于限制应用程序中Kotlin的类, 接口, 方法和属性的使用。这些修饰符可在多个地方使用, 例如类标题或方法主体。

在Kotlin中, 可见性修改器分为四种不同类型:

  • 上市
  • 受保护的
  • 内部
  • 私人的

公开编辑

可从项目中的任何地方访问public修饰符。它是Kotlin中的默认修饰符。如果未使用任何访问修饰符指定任何类, 接口等, 则在公共范围内使用该类, 接口等。

public class Example{
}
class Demo{
}
public fun hello()
fun demo()
public val x = 5
val y = 10

所有公共声明都可以放在文件顶部。如果未指定class的成员, 则默认情况下为public。

受保护的修饰符

具有类或接口的受保护修饰符仅允许对其类或子类可见。除非显式更改其子类中的受保护的声明(在重写时), 否则它也是受保护的修饰符。

open class Base{
    protected val i = 0
}

class Derived : Base(){

    fun getValue() : Int
    {
        return i
    }
}

在Kotlin中, 不能在顶层声明protected修饰符。

覆盖受保护的类型

open class Base{
  open protected val i = 5
}
class Another : Base(){
    fun getValue() : Int
    {
        return i
    }
    override val i =10
}

内部编辑

内部修饰符是Kotlin中新添加的, 在Java中不可用。声明任何内容都会将该字段标记为内部字段。内部修饰符使该字段仅在实现它的模块内部可见。

internal class Example{
    internal val x = 5
    internal fun getValue(){

    }
}
internal val y = 10

在上面, 所有字段都声明为内部字段, 这些字段只能在实现它们的模块内部访问。

私人编辑

私有修饰符仅允许在声明属性, 字段等的块内访问该声明。 private修饰符声明不允许访问范围的外部。可以在该特定文件中访问私有软件包。

private class Example {
    private val x = 1
     private valdoSomething() {
    }
}

在上面的类Example中, val x和函数doSomthing()被声明为private。可以从同一源文件访问“示例”类, 在示例类中可以访问“ val x”和“ fun doSomthing()”。

可见性修改器示例

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<String>) {
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
}
赞(1)
未经允许不得转载:srcmini » Kotlin可见性修改器

评论 抢沙发

评论前必须登录!