Javatpoint Logo
Javatpoint Logo

Kotlin Visibility Modifier

Visibility modifiers are the keywords which are used to restrict the use of class, interface, methods, and property of Kotlin in the application. These modifiers are used at multiple places such as class header or method body.

In Kotlin, visibility modifiers are categorized into four different types:

  • public
  • protected
  • internal
  • private

public modifier

A public modifier is accessible from everywhere in the project. It is a default modifier in Kotlin. If any class, interface etc. are not specified with any access modifier then that class, interface etc. are used in public scope.

All public declaration can be placed at top of the file. If a member of class is not specified then it is by default public.

protected modifier

A protected modifier with class or interface allows visibility to its class or subclass only. A protected declaration (when overridden) in its subclass is also protected modifier unless it is explicitly changed.

In Kotlin, protected modifier cannot be declared at top level.

Overriding of protected types

internal modifier

The internal modifiers are newly added in Kotlin, it is not available in Java. Declaring anything makes that field marked as internal field. The internal modifier makes the field visible only inside the module in which it is implemented.

In above, all the fields are declared as internal which are accessible only inside the module in which they are implemented.

private modifier

A private modifier allows the declaration to be accessible only within the block in which properties, fields, etc. are declare. The private modifier declaration does not allow to access the outside the scope. A private package can be accessible within that specific file.

In above class Example,val x and function doSomthing() are declared as private. The class "Example" is accessible from the same source file, "val x" and "fun doSomthing()" are accessible within Example class.

Example of Visibility Modifier

Next TopicKotlin Inheritance

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA