Encapsulation in Java – Encapsulation is one of the fundamental Object Oriented Programming (OOP) concepts. The other fundamentals are inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit.
Why Is Encapsulation?
It’s because encapsulation has a number of benefit that make the easy reusability, flexibility and maintainability of the code.
- Flexibility: It’s more flexible and easy to change and maintable the encapsulated code with new requirements. For example, if the requirement for setting the age of a person changes, we can easily update the logic in the setter method setAge().
- Reusability: Encapsulated code can be reused throughout the project or across multiple projects. For example, the Person class can be reused whenever such type of object is required.
- Maintainability: Application ode is encapsulated in separate units (classes, interfaces, methods, setters, getters, etc) so it’s easy to make any change or update specific point of the application without affecting other parts, which reduces the time of maintenance.
How Is Encapsulation Done in Java?
As you can video with examples, encapsulation is implemented in Java using interfaces, classes, access modifiers, setters and getters.