46. Visibility modifiers in Kotlin: public, private, protected, and internal

🔒 Visibility Modifiers in Kotlin: Controlling Code Access

Welcome, Kotlin developers! Understanding visibility modifiers is crucial for creating robust and secure applications. In this comprehensive guide, we'll explore how Kotlin's visibility modifiers help you control access to classes, methods, and properties.

📍 What are Visibility Modifiers?

Visibility modifiers are keywords that define the accessibility of classes, objects, interfaces, constructors, functions, properties, and their setters. Kotlin provides four main visibility modifiers:

  • public
  • private
  • protected
  • internal

🔑 Public Modifier

The most permissive visibility modifier that allows unrestricted access from anywhere.

public class User {
    public val name: String = "John Doe"
    public fun sayHello() {
        println("Hello!")
    }
}

🔐 Private Modifier

Restricts visibility to the same class or file.

class SecretKeeper {
    private val secretCode = 12345
    
    fun validateSecret(code: Int): Boolean {
        return code == secretCode
    }
}

🛡️ Protected Modifier

Accessible within the class and its subclasses.

open class BaseClass {
    protected val protectedValue = 100
    
    protected fun protectedMethod() {
        println("This method is protected")
    }
}

class DerivedClass : BaseClass() {
    fun accessProtected() {
        println(protectedValue) // Allowed
        protectedMethod() // Allowed
    }
}

🌐 Internal Modifier

Visible within the same module (compilation unit).

internal class ModuleSpecificClass {
    internal fun moduleFunction() {
        println("Only visible within the same module")
    }
}

🏋️ Practical Exercises

1. Create a class with mixed visibility modifiers 2. Implement inheritance demonstrating protected access 3. Design a module with internal classes 4. Develop a secure authentication system using private methods 5. Create a utility class with controlled access levels
Pro Tip: Always use the most restrictive visibility modifier that meets your design requirements.

📌 Key Takeaways

  • Visibility modifiers help control code accessibility
  • Choose the right modifier for better encapsulation
  • Public is default, but not always recommended
  • Internal is great for module-level encapsulation
#Kotlin #JavascriptAcademy #ProgrammingTips #CodeSecurity

📱 Stay Updated with Android Tips!

Join our Telegram channel for exclusive content, useful tips, and the latest Android updates!

👉 Join Our Telegram Channel

Get daily updates and be part of our growing Android community!

Comments

Popular posts from this blog

2. Comments in Kotlin: Single-line, multi-line, and KDoc

10. Long data type in Kotlin programming language

1. What is Kotlin programming language and how does it differ from Java?