In Kotlin, visibility modifiers limit the accessibility of classes, objects, interfaces, constructors, functions, properties, and their setters to a certain level. The visibility of the getters does not need to be set because they have the same visibility of the property. Kotlin has four visibility modifiers:
Modifier | Description |
---|---|
Public | It is visible everywhere. |
Private | It is visible inside the same class only. |
Internal | It is visible inside the same module. |
Protected | It is visible inside the same class and subclasses. |
Note: If there is no specific modifier, it is public by default.
In Kotlin, the default modifier is general. It may be the most widely used modifier in the entire language, and there are additional restrictions on who can modify this component. Unlike in Java, there is no need to declare anything public in Kotlin; it is the default modifier unless we announce another modifier - public works in Kotlin as in Java. When we apply a public modifier to top-level components, classes, functions, or variables directly declared within a package, and any other code can access it. If we use a public modifier to a nested element; an internal class, or work within a class; then this component can access any code the container can access.
In Kotlin, private modifiers allow access only to code declared within the same range, and it does not allow access to the modifier variable or operations outside the scope. Unlike Java, Kotlin allows multiple top-level declarations in the same file; everything else in the same file can access a private top-level component.
In Kotlin, the internal modifier is a newly added modifier that does not support Java. Internally marked as available in the same module, it will give an error if you try to access the declaration from another module. Module means a set of files compiled together.
In Kotlin, the protected modifier strictly allows access to the declaration class and its subdivisions. The protected modifier cannot be declared high level. In the following program, we have accessed the int variable in the getvalue () function of the derivative class.
|