Skip to content
Abhishek Khare edited this page Jan 9, 2017 · 7 revisions

Encapsulation(Data Hiding)

  1. The beauty of encapsulation is the power of changing things without affecting its users.
  2. In Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes.
  3. The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users.
  4. There are several reasons why you might want to encapsulate access to your fields. For example:
    • You can limit the values that can be stored in a field
    • You can take actions when the field is modified (trigger event, validate, etc).
    • You can provide thread safety by synchronizing the method.
    • You can switch to a new data representation (i.e. calculated fields, different data type)
    • Encapsulated Code is more flexible and easy to change with new requirements.
    • Encapsulation in Java makes unit testing easy.
    • Encapsulation in Java allows you to control who can access what.
    • Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environment.
    • Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing are encapsulated in one place.
    • Encapsulation allows you to change one part of code without affecting other part of code.
    • Example in Java is Arrays.asList().

Clone this wiki locally