Visibility modifiers
When you define your class, the contained methods, properties, or fields can have various visibility levels. In Kotlin, there are four possible values:
Public: This can be accessed from anywhere
Internal: This can only be accessed from the module code
Protected: This can only be accessed from the class defining it and any derived classes
Private: This can only be accessed from the scope of the class defining it
If the parent class specifies that a given field is open for being redefined (overwritten), the derived class will be able to modify the visibility level. Here is an example:
open class Container { protected open val fieldA: String = "Some value" } class DerivedContainer : Container() { public override val fieldA: String = "Something else" }
Now in the main class, you can create a new DerivedContainer
instance and print out the value of fieldA
. Yes, this field is now public to any code:
val derivedContainer...