Encapsulation in Java
→ Encapsulation is a process of wrapping data/variables with methods.
→ It helps to archive data hiding in java from outside world.
→ we can use setter and getter methods to set and get the data in it.
Advantage of Encapsulation in java
- By providing only setter or getter method, you can make the class read-only or write-only.
- Key benefit of that - Encapsulation provides ability to make changes in your code without breaking the code of others who use your code.
- By hiding implementation details, we can rework our method code without forcing a change in the code that calls your changed method.
- Encapsulation provides maintainability, flexibility, and extensibility to our application.
- Encapsulation provides more flexible and easy to change with new requirements.
- Encapsulation in Java makes unit testing easy.
- Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environment.
Example:-
Output
|