ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Visibility Control in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='95' AND `tutorial_status`=1 LIMIT 1

Visibility Control in Kotlin

📌 Visibility Control in Kotlin

In Kotlin, visibility modifiers are used to control the access to classes, objects, functions, properties, and constructors. Kotlin provides four visibility modifiers:

  1. public → Visible everywhere (default)

  2. private → Visible only within the same class or file

  3. protected → Visible within the class and its subclasses

  4. internal → Visible within the same module


✅ 1. public (Default Modifier)

  • The default visibility modifier in Kotlin.

  • Accessible from anywhere in the project.

📌 Example:

kotlin

fun () { println("Name: $name") }}class Person(private val name: String) { private fun () { println("Name: $name") } fun () { showName() // Accessible within the class }}val person = Person("Vikash")person.callShowName() // Accessible// person.showName() // Error: Cannot access 'showName'

  • For Top-Level Declarations (Functions, Variables)

kotlin

private val apiKey = "12345"private fun () { println("This is a secret function.")}

These will only be accessible within the same file.


✅ 3. protected

  • Accessible within the class and its subclasses.

  • Not accessible outside the class hierarchy.

📌 Example:

kotlin

open class Animal { protected fun () { println("Animal makes sound") }}class Dog : Animal() { fun () { sound() // Accessible in subclass println("Dog barks") }}val dog = Dog()dog.bark()// dog.sound() // Error: Cannot access 'sound'


✅ 4. internal

  • Accessible within the same module.

  • Useful when working on large projects with multiple modules.

  • Modules are typically .jar or .aar files.

📌 Example:

kotlin

internal class Car(val model: String) { internal fun () { println("Car Model: $model") }}val car = Car("Tesla")car.displayModel() // Accessible within the same module


✅ Visibility Modifier Summary

ModifierClass Members Accessible FromTop-Level Declarations Accessible FromNotes
publicAnywhereAnywhereDefault visibility
privateWithin the same class or fileWithin the same fileHides implementation details
protectedSame class and subclassesN/ANot applicable to top-level functions
internalWithin the same moduleWithin the same moduleUseful for module-based projects


✅ Conclusion

  • Use public when you want full accessibility.

  • Use private to restrict access within a class or file.

  • Use protected for inheritance and subclass-level access.

  • Use internal to maintain accessibility within a module.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql