Java Encapsulation:

  • Encapsulation is a mechanism where we collect code (methods) as a unit while working on data (variables) and data.
  • In java encapsulation, the variables of one class will be hidden from other sections, and can be accessed only through the methods of their current class, therefore, this is also known as data hiding.
  • In order to achieve the encapsulation, we need to declare the variable of one class as private and to provide a public setter and a getter method for modifying and viewing variable values.


To get encapsulation in Java:

  • Announce a class variable as a private.
  • Provide public setter and getter methods for modifying and viewing variable values.
  • It gives you control over the data.


Benefits of Encapsulation:

  • Hide data: The user will not have any information about the internal implementation of the class. It will not be visible to the user, how the values ​​are stored in the client variable.
  • Rising Flexibility: Based on our requirement, we can only read or write only the variables of the class.
  • Reusability: improvisation with improvisation and new requirements is improved easily with java encapsulation.
  • The test code is simple: it is easy to check for unit testing.