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:
public→ Visible everywhere (default)private→ Visible only within the same class or fileprotected→ Visible within the class and its subclassesinternal→ Visible within the same module
✅ 1. public (Default Modifier)
The default visibility modifier in Kotlin.
Accessible from anywhere in the project.
📌 Example:
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)
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:
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
.jaror.aarfiles.
📌 Example:
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
| Modifier | Class Members Accessible From | Top-Level Declarations Accessible From | Notes |
|---|---|---|---|
public | Anywhere | Anywhere | Default visibility |
private | Within the same class or file | Within the same file | Hides implementation details |
protected | Same class and subclasses | N/A | Not applicable to top-level functions |
internal | Within the same module | Within the same module | Useful for module-based projects |
✅ Conclusion
Use
publicwhen you want full accessibility.Use
privateto restrict access within a class or file.Use
protectedfor inheritance and subclass-level access.Use
internalto maintain accessibility within a module.