Visibility modifiers are that set the accessibility (visibility) of Classes, objects, interfaces, constructors, functions, properties, and their setters.
There are four types of visibility modifiers,
Public
Private
Protected
Internal
Getters always have the same visibility as the properties.
Visibility Modifiers inside Packages: Functions, properties, and classes, objects and interfaces can be declared on the "top-level", i.e. directly inside a package,
public: Visible everywhere, The default visibility, if there is not an explicit modifier
private: Visible inside the file containing the declaration.
internal: Visible everywhere with the same module.
protected: Not available for top-level declaration.
Local variables, functions, and classes can not have visibility modifiers.
To specify the visibility of the primary constructor of a class, use the following syntax (by default constructors are public),
Program to demonstrate the example of Example of various visibility modifiers on package level in Kotlin
package com.includehelp
// Public by default, visible to everywhere
fun fun1(){
// local variable can not have visibility
var a=5
println("Inside Fun1 $a")
}
// private , visible inside Containing file
// VisibilityModifiersInsidePackages.kt
private fun fun2(){
println("Inside Fun2")
}
// internal , visible inside same module
internal fun fun3(){
println("Inside Fun3")
}
// public by default visible everywhere
var name="IncludeHelp"
// by default public, visible every where
class MyClass
// Main function, Entry point of program
fun main(){
// call function
fun1()
// call function
fun2()
// call function
fun3()
//Access variable
println("Name : $name")
}
Output:
Inside Fun1 5
Inside Fun2
Inside Fun3
Name : IncludeHelp
Program to demonstrate the example of Example of various visibility modifiers on package level in Kotlin
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer