The Techie King

Encapsulation in java

Article By The Techie King

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.

Way to achieve encapsulation in Java

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.

Benefits of Encapsulation

  • The fields of a class can be made read-only or write-only.
  • A class can have total control over what is stored in its fields.
  • Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user how the class is storing values in the variables. The user will only know that we are passing the values to a setter method and variables are getting initialized with that value.
  • Reusability: Encapsulation also improves the re-usability and is easy to change with new requirements.

Scroll to Top