Start a Project

Visibility Modifiers in Kotlin

Visibility modifiers in Kotlin are keywords that set the visibility of classes, objects, interfaces, constructors, functions, and properties.

Types of Visibility Modifiers

There are Four types of visibility modifiers in Kotlin.

The purpose of modifiers is to provide accessibility to classes, objects, functions, etc.
Basically, there is no need to set modifiers for getters as they have the same visibility as their properties.
Public Modifier is the default modifier in Kotlin.

Public Modifier

It is the default visibility modifier in Kotlin.
Classes, variables, and interfaces are visible everywhere which are public. It is also a frequently used modifier.
Generally used when no need to implement restrictions on field function and variables.

For Example :

 Private Modifier

Private modifiers are only allowed within the block in which property is declared. It does not allow outside access.
A private package can only be accessible within that specific file. Generally used when implementing more restrictions on field function and variables.

For Example :

 Protected Modifier

Protected modifier with class and interface only visible to its class or subclass
An overridden, protected declaration in its subclass will also be a protected modifier until we change explicitly. Generally used when implementing more restrictions on field function and variables.

 Internal Modifier

The internal modifier makes the field visible only inside the module. Error Will through if we access any field outside the module. Generally used with Api-related Work.

For Example

Conculusion

In this blog, we have discussed about the Visibility modifiers in Kotlin

Thank you for reading!!

Exit mobile version