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
📌 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
📱 Stay Updated with Android Tips!
Join our Telegram channel for exclusive content, useful tips, and the latest Android updates!
👉 Join Our Telegram ChannelGet daily updates and be part of our growing Android community!
Comments
Post a Comment