Encapsulation is a way of restricting data and methods that are exposed to users of a class.

When you define a class, you specify the type of Access modes each data member and method will have at runtime. The benefits of encapsulation are:

  • Only what is needed to interact with a class instance is exposed. Other parts of the application are shielded from (and do not need to know about) implementation details or changes.
  • The implementation of the behavior is localized.
  • Code is easy to maintain.
Note: The best practice is to hide as much data as possible until a valid case is made for making the access mode less restrictive.