ADVERTISEMENT
ADVERTISEMENT

Kotlin program | Example of Various Visibility Modifiers

Kotlin | Various Visibility Modifiers: Here, we are implementing a Kotlin program to demonstrate the example of various visibility modifiers.
Submitted by IncludeHelp, on June 12, 2020

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) { ... }
    

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.