Loading, please wait...

A to Z Full Forms and Acronyms

What is the visibility Modifier in Kotlin? | Kotlin Tutorial

Jan 26, 2022 #KotlinLanguage #Programming, 1110 Views
In this article, you will learn about the visibility modifier and its type.

What is the visibility Modifier in Kotlin? | Kotlin Tutorial

In this article, you will learn about the visibility modifier and its type.

The keywords which restrict the accessibility of properties in class, interface, methods, and property of kotlin in the application is known as visibility modifier. These modifiers are used in the class header and method body to put the restriction. 

There are four types of visibility modifiers in kotlin similar to other programming languages:

  • private
  • public
  • protected
  • internal

With the help of these modifiers, we apply the limitation on the accessibility of the class, method, and interfaces. 

private modifier

A private modifier does not allow the data elements to be accessed outside the block. It allows the declaration to be accessible only inside the block in which properties, fields, elements, and more are declared. It is accessible only within the specified file. 

Syntax:

Private class class_name{

   private variable

}

The variable declared inside this class is accessible only in this class.

 

public modifier

It is the default modifier in the kotlin language. The public modifier is accessible from anywhere in the class. If the class, interface, and method are not specified with any modifier then by default its specifier is public. The public modifier declaration can be placed at the top of the file. 

Syntax:

public class class_name{

   #body of the class

}

class class_name{

  #body of the class 

}

protected modifier

The protected modifier allows visibility in its class and subclass only. A protected element declared in the class is also protected in its subclass unless it is explicitly changed. There is no need to declare the protected modifier at the top level.

Syntax:

open class class_base{  

protected val j = 0  

}  

class class_derived : class_base(){  

fun getValue() : Int  

{  

   return j 

}  

}

internal modifier

It is a new modifier in the kotlin language. It is not available in other programming languages. It makes the field visible only inside the module in which it is implemented. 

A to Z Full Forms and Acronyms

Related Article