Kotlin Encapsulation is one of the core concepts of an Object-oriented programming language. It restricts direct access to certain object components through direct access to outside modifiers, and they can be modified using member functions/modifiers (getter and setter) only. That makes the code more secure and modular.
Kotlin Encapsulation: A Beginner’s Guide with Examples
Kotlin has four modifiers: Private, Protected, Internal, and Public, which control access to class member variables and functions.
- Private Modifier: When we apply private to a function or variable(property), it’s accessible only within the class in which it’s declared. To modify its value we have to use getter and setter. If we declare a function as private outside of a class scope then it is only accessible to that file only.
123456789101112131415161718class CommonMessage() {private fun printWelcomeMessage() {println("Welcome ... !!")}}fun main() {val tempObject = CommonMessage()tempObject.printWelcomeMessage()}// Output// Cannot access 'fun printWelcomeMessage(): Unit': it is private in '/CommonMessage'. - Protected Modifier: Protected allows access of methods and properties(variables) to the same class and its subclass. Here subclass means inheritance class. If you want to learn more about inheritance then read this tutorial.
12345678910111213141516171819202122232425open class CommonMessage() {protected fun printWelcomeMessage() {println("Welcome ... !!")}}class AllMessages() : CommonMessage(){fun printMessage(){printWelcomeMessage()}}fun main() {val allObject = AllMessages()allObject.printMessage()}// OutputWelcome ... !! - Internal Modifier: The internal modifier allows a class or its functions and member variables to be accessed within the same module. It is useful when you have a large project and only want to share code within the same modules.
1234567891011121314151617internal class CommonMessage() {internal fun printWelcomeMessage() {println("Welcome ... !!")}}fun main() {val tempObj = CommonMessage()tempObj.printWelcomeMessage()}// OutputWelcome ... !! - Public Modifier(Default): In Kotlin public modifier is the default modifier, meaning if you cannot specify a modifier then by default it is public. All publically declared variables and functions can be accessed from any other class or its object.
1234567891011121314class CommonMessage() {fun printWelcomeMessage() {println("Welcome ... !!")}}fun main() {val tempObj = CommonMessage()tempObj.printWelcomeMessage()}
Conclusion:
In this tutorial, we have explained how encapsulation works in Kotlin. Using encapsulation makes our code secure and maintainable. So keep practicing and you will master the basics of Kotlin.