Encapsulation In OOPs
October 15th 2020 581
Encapsulation in Java is a process of wrapping code and data together into a single unit. The best way to understand encapsulation is to look at the example of a medical capsule, where the drug is always safe inside the capsule. Similarly, through encapsulation the methods and variables of a class are well hidden and safe.
We can achieve encapsulation in Java by:
- Declaring the variables of a class as private.
- Providing public setter and getter methods to modify and view the variables values.
Often encapsulation is misunderstood with Abstraction.
- Encapsulation is more about "How" to achieve a functionality.
- Abstraction is more about "What" a class can do.
A simple example to understand this difference is a mobile phone. Where the complex logic in the circuit board is encapsulated in a touch screen, and the interface is provided to abstract it out.
Simple Java program to demonstrate encapsulation:
Advantages of Encapsulation:
- The user will have no idea about the inner implementation of the class.
- We can make the variables of the class as read-only or write-only depending on our requirement.
- Encapsulation also improves re-usability and is easy to change with new requirements.
- Encapsulated code is easy to test for unit testing.