原文: https://beginnersbook.com/2019/03/kotlin-visibility-modifiers/
可见性修饰符将类,接口,函数,属性,构造函数等的访问限制到某个级别。在 kotlin 中,我们有四个可见性修饰符 - 公共,私有,受保护和内部。在本指南中,我们将借助示例了解这些可见性修饰符。
Kotlin 可见性修饰符
public:在任何地方都可见,这是 Kotlin 中的默认可见性修饰符,这意味着如果你没有指定修饰符,它默认是公共的。private:包含声明的文件内可见。如果数据成员或成员函数在类中声明为private,则它们仅在类中可见。protected:内部类和子类可见。internal:在同一模块内可见。
让我们举个例子。在下面的示例中,我们有一个文件Example.kt,我们已经在文件中声明了一个数据成员,几个成员函数和一个类。注释中提到了每一个的可见性。
// file name: Example.ktpackage beginnersbook.com// public so visible everywherevar str = "BeginnersBook"// By default public so visible everywherefun demo() {}// private so visible inside Example.kt onlyprivate fun demo2() {}// visible inside the same moduleinternal fun demo3() {}// private so visible inside Example.ktprivate class MyClass {}
Kotlin 可见性修饰符示例
在这个例子中,我们有两个类Parent类和Child类。我们在示例中使用了所有四种类型的可见性修饰符,请通过注释来了解当前类和子类中每个数据成员和成员函数的可见性。
// file name: Example.ktpackage beginnersbook.comopen class Parent() {// by default publicvar num = 100// visible to this this class onlyprivate var str = "BeginnersBook"// visible to this class and the child classprotected open val ch = 'A'// visible inside the same moduleinternal val number = 99// visible to this class and child classopen protected fun demo() { }}class Child: Parent() {/* num, ch, number and function demo() are* visible in this class but str is not visible.*/override val ch = 'Z'override fun demo(){println("demo function of child class")}}fun main(args: Array<String>) {/* obj.num and obj.number are visible* obj.ch, obj.demo() and obj.str not visible*/val obj = Parent()/* obj2.ch and obj2.demo() are not visible because if* you override protected members in child class without* specifying modifier then they are by default protected*/val obj2 = Child()}
