在本教程中,我们将讨论 Kotlin 编程中可用的各种可见性修改器。
Kotlin 可见性更改器
可见性编辑器是编辑器,当在 Kotlin 中附加到类/接口/属性/函数时,会定义所有可见性在哪里,以及从哪里可以访问所有可见性。 Kotlin 中的属性设置器可以从属性中具有单独的编辑器。
- 公共
- 保护
- 内部
- 私人
公共变更
Public Modifier 是 Kotlin 中的默认编辑器,就像 Java 公共编辑器一样,它意味着声明到处都是可见的。
1class Hello{
2}
3
4public class H{
5}
6
7fun hi()
8public fun hello()
9
10val i = 0
11public val j = 5
上面的所有声明都是文件的顶层声明. 所有声明都是公开的. 如果我们不提到班级成员的声明,它们都是公开的(除非它们被夸大)。
受保护的变更
A Protected Modifier in Kotlin: CANNOT be set on top-level declarations. Declarations that are protected in a class, can be accessed only in their subclasses.
1open class Pr{
2 protected val i = 0
3}
4
5class Another : Pr{
6
7 fun iValue() : Int
8 {
9 return i
10 }
11}
非 Pr 子类的类不能访问受保护的 i
声明,如果 overridden 在子类中具有相同的受保护的修改者,除非您明确更改它们。
1open class Pr{
2 open protected val i = 0
3}
4
5class Another : Pr(){
6
7 fun iValue() : Int
8 {
9 return i
10 }
11
12 override val i = 5 //protected visibility
13}
Kotlin 中所定义的受保护的修改器的概念与 Java 中的概念不同。
内部变更
内部是Kotlin中可用的新的修改程序,在Java中不存在。将声明设置为内部意味着它只在同一个模块中可用。
1internal class A {
2}
3
4internal val x = 0
这些不会在当前模块之外可见。内部修改器在需要隐藏用户的特定库实现时是有用的。
个人变更
私人修改器不允许声明在当前范围之外可见。
1var setterVisibility: String = "abc"
2private set
3
4open class Pr{
5 open protected val i = 0
6
7 fun iValue() : Int
8 {
9 setterVisibility = 10
10 return setterVisibility
11 }
12}
由于 kotlin 允许多个顶级定义,所以上面的代码是有效的。
1private open class ABC{
2 private val x = 6
3}
4
5private class BDE : ABC()
6{
7 fun getX()
8 {
9 return x //x cannot be accessed here.
10 }
11}
x 只能从其类内部可见,我们可以用以下方式设置私人构造器:
1class PRIV private constructor(a: String) {
2 ...
3}
默认的类有公共编辑器. 无论该类去哪里,编辑器都遵循。 我们需要在定义中将可见性编辑器设置在编辑器上。 因此,Kotlin使用保护和内部编辑器不同于Java。 此外,Java的默认编辑器是包私有,但在Kotlin中还不存在。