Visibility modifiers restrict the access of classes, interfaces, functions, properties, constructors etc. to a certain level. In kotlin we have four visibility modifiers – public, private, protected and internal. In this guide, we will learn about these visibility modifiers with the help of examples.
Kotlin Visibility Modifiers
public: visible everywhere, this is the default visibility modifier in Kotlin which means if you do not specify the modifier, it is by default public.
private: visible inside the file containing the declaration. If a data member or member function is declared private in a class then they are visible in the class only.
protected: Visible inside class and subclasses.
internal: visible inside the same module.
Lets take an example. In the following example we have a file Example.kt and we have declared a data member, few member functions and a class inside the file. The visibility of each one of them is mentioned in the comments.
// file name: Example.kt package beginnersbook.com // public so visible everywhere var str = "BeginnersBook" // By default public so visible everywhere fun demo() {} // private so visible inside Example.kt only private fun demo2() {} // visible inside the same module internal fun demo3() {} // private so visible inside Example.kt private class MyClass {}
Kotlin visibility modifier example
In this example, we have two classes Parent
class and Child
class. We have used all four types of visibility modifiers in the example, please go through the comments to understand the visibility of each data member and member function in the current class and subclass.
// file name: Example.kt package beginnersbook.com open class Parent() { // by default public var num = 100 // visible to this this class only private var str = "BeginnersBook" // visible to this class and the child class protected open val ch = 'A' // visible inside the same module internal val number = 99 // visible to this class and child class open 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() }
Leave a Reply