在本教程中,我们将讨论Kotlin编程中可用的各种可见性修饰符。
Kotlin可见性修饰符
可见性修饰符是一种修饰符,当附加到Kotlin中的类/接口/属性/函数时,可以定义它在哪里可见以及从哪里可以访问。 Kotlin中的属性的setter可以具有与属性不同的修饰符。getter不能有可见性修饰符。它们使用与属性相同的修饰符。以下是可见性修饰符:
- public
- protected
- internal
- private
公共修饰符
A Public Modifier is the default modifier in Kotlin. Just like the Java public modifier, it means that the declaration is visible everywhere.
class Hello{
}
public class H{
}
fun hi()
public fun hello()
val i = 0
public 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.
open class Pr{
protected val i = 0
}
class Another : Pr{
fun iValue() : Int
{
return i
}
}
類別若非 Pr 的子類別,則無法存取 i
在子類別中被覆寫時,如果保護修飾符相同,則除非您明確更改,否則會與父類別中的保護修飾符相同。
open class Pr{
open protected val i = 0
}
class Another : Pr(){
fun iValue() : Int
{
return i
}
override val i = 5 //protected visibility
}
上面定義的 Kotlin 中的 Protected 修飾符概念與 Java 中的不同。
Internal 修飾符
Internal 是 Kotlin 中的一個新修飾符,Java 中沒有。將宣告設為 internal 意味著它只會在同一模組中可用。在 Kotlin 中,模組指的是一組一起編譯的文件。
internal class A {
}
internal val x = 0
這些在當前模組之外是不可見的。內部修飾符在您需要隱藏特定庫實現時很有用。這在 Java 中使用 package-private 可見性是不可能的。
私有修飾符
私有修飾符不允許宣告在當前範圍之外可見。
var setterVisibility: String = "abc"
private set
open class Pr{
open protected val i = 0
fun iValue() : Int
{
setterVisibility = 10
return setterVisibility
}
}
由於 Kotlin 允許多個頂級定義,因此上面的程式碼有效。下面的程式碼則不行。
private open class ABC{
private val x = 6
}
private class BDE : ABC()
{
fun getX()
{
return x //x cannot be accessed here.
}
}
x is visibile only from inside its class. We can set private constructors in the following way:
class PRIV private constructor(a: String) {
...
}
{
“error”: “Upstream error…”
}