Kotlin Encapsulation: A Beginner’s Guide with Examples

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 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.

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.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *