What are Kotlin visibility modifiers :
In Kotlin, we can define a class member as private, internal, public or protected. These are also called visibility modifiers. It defines the scope from where we can access a member.
In this tutorial, we will learn how these visibility modifiers works with examples.
Private visibility modifier :
Private members are only visible inside the class. private keyword is used to make one property private. For example :
open class Example{
val name = "Alex"
}
class SubExample : Example(){
fun printHelloFromInside(){
print("Hello $name !")
}
}
This program will work. But if we make name private, it will not work. If name becomes private, it will be accessible only inside the class Example.
Internal visibility modifier :
Internal visibility modifier makes one property visible to only in the same module. This is not available in Java. internal keyword is used for it. Module is a set of files that compiles together.
For example :
internal val myNumber = 4
internal open class InternalClass{
}
internal visibility modifier is really useful for library implementation. We can make all classes hidden from the application that uses the library and we don’t want the application to get access to these classes.
Protected visibility modifier :
protected keyword is used for protected visibility modifier. It makes one property visible to a class and its subclasses. It is same as private modifier but only visible to its subclasses.
Note that we can’t set it on top-level declaration. Let’s consider the same example we have used for private :
open class Example{
protected val name = "Alex"
}
class SubExample : Example(){
fun printHelloFromInside(){
print("Hello $name !")
}
}
This will work.
In the subclass also, it has the same protected modifier. But you can explicitly change them.
Public visibility modifier :
This is the default modifier in Kotlin. It will make one property visible to everywhere. For example :
class Example{
}
public class Example2{
}
public var number = 10
var number2 = 20
All of these above properties are public.
Visibility of a constructor :
By default, the constructor is public in Kotlin classes. They are visible to all places where the class is visible. To explicitly change the constructor visibility, we need to use constructor keyword.
For example :
class Example private constructor(val num: Int){
}
This is a private constructor for the class Example.