Java Encapsulation

 

    Encapsulation is the process of organizing data into a single unit. It is the connection point between the code and the data it works with. Encapsulation can instead be understood as a protective shield that keeps code outside of it from accessing the data. 

    Its look like a real world capsule. In a real world capsule, we store medicine as a one unit. In java programming , we store data as a one unit for protecting the data.

Access Modifiers:-

    We use some access modifiers for data security.

  • public -  Members of the public are accessible from any class, regardless of whether it is part of the same package or not. The Private Access Modifier is the most secure.
  • private -Members (fields or methods) declared as private are only accessible within the same class.
  • default -Members with default access are accessible within the same package but not outside of it.
  • protected - Protected members are accessible within the same class, same package, and by subclasses (even if they are in a different package).

Getter & Setters:-

    In Java, Getter and Setter are methods used to protect your data and make your code more secure. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type.

    We can extract the private data by using get and set method (encapsulate). For that we use getter setter.

    Getter methods allow retrieving the values of private fields. Setter methods allow modifying the values of private fields while providing a level of control and validation.

    We make data private for data security. But sometimes we may need that private data for other classes. This getter setter is used to provide the necessary data when need in other classes.

    By providing controlled access to the internal state of a class through getter and setter methods, encapsulation is maintained, and the class can enforce its own rules and validations for accessing and modifying its data.



Advantages of encapsulations:-



  • Data hiding.
  • Data privacy.
  • Access controlling.
  • Testing code easily.
  • Flexibility.

Disadvantages of encapsulations:-

  • Can lead to increased complexity, especially if not used properly.
  • Can make it more difficult to understand how the system works.
  • May limit the flexibility of the implementation.



Comments

Popular posts from this blog

අද අපි කතා කරමු Data collections ගැන

Understanding and Mastering Coding Errors

OOP key points