Encapsulation in Java or object-oriented programming language is a concept that enforces protecting variables, functions from outside of class, in order to better manage that piece of code and having the least impact or no impact on other parts of a program due to change in protected code.
Encapsulation in Java is visible at different places for instance
You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifiers like protected or the public.
Advantage of Encapsulation
- 1. “Whatever changes encapsulate it” is a famous design principle.
- 2. Encapsulation helps in loose coupling and high cohesion of code.
- 3. Encapsulation in Java is achieved using access modifiers private, protected, and public.
- 4. Factory pattern, Singleton pattern in Java makes good use of Encapsulation.
What should you encapsulate in code
Anything which can be change and more likely to change in the near future is a candidate of Encapsulation. This also helps to write a more specific and cohesive code. An example of this is object creation code, code which can be improved in the future like sorting and searching logic.
Design Pattern based on Encapsulation in Java
Factory pattern is used to create objects. Factory pattern is a better choice than a new operator for creating an object of those classes whose creation logic can vary and also for creating a different implementation of the same interface.
Singleton pattern in Java also encapsulates how you create an instance by providing a getInstance() method.