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 for members declared inside class and interfaces,
public: Vsible to any client who can see declaring class.
private: Visible inside the class only.
protected: Visible inside the class(same as private) and visible in subclasses too.
internal: Visible to any client inside the module who can see declaring class.
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 Various Visibility Modifiers in Kotlin
package com.includehelp
// Class, by default public visibility
// Mark with 'open' to make inheritable
open class MyOuter{
private var myname="IncludeHelp India !!"
protected open val age=30
internal var salary=100
var city="Delhi" // Public , by default
protected fun fun1(){
println("Protected Function in Base !!")
}
}
class MySub: MyOuter() {
// Override protected members,
// because protected is visible in subclass
override val age: Int
get() = 50
fun printDetails(){
// Can't Access $myname as it is private in super class
// println("Name : $myname")
println("City : $city")
println("Salary : $salary")
println("Age : $age")
}
}
// Main function, Entry Point of Program
fun main(){
// Create Instance
val myOuter = MySub()
// Call subclass method
myOuter.printDetails()
}
Program to demonstrate the example of Various Visibility Modifiers in Kotlin
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer