Q:

Kotlin program | Example of Various Visibility Modifiers

belongs to collection: Kotlin Class and Object Programs

0

Visibility Modifiers

  • 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,
    1. Public
    2. Private
    3. Protected
    4. Internal
  • Getters always have the same visibility as the properties.
  • Visibility modifiers for members declared inside class and interfaces,
    1. public: Vsible to any client who can see declaring class.
    2. private: Visible inside the class only.
    3. protected: Visible inside the class(same as private) and visible in subclasses too.
    4. 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),
    class C private constructor(a: Int) { ... }

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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()
}

Output:

City :  Delhi
Salary : 100
Age : 50

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program | Example of abstract class... >>
<< Kotlin program | Example of class and object (with...