What is Encapsulation (Data-Hiding) in Java?
- Encapsulation is the process of hiding the object’s properties from the outside of the class. And providing the methods to access them outside of the class.
- Java POJO class (getter-setter class) is a good example for encapsulation in java. In this class, we have private variables and to access them we have getter and setter methods.
- Since encapsulation is used to hide the data it’s also called Data-hiding.
- Using encapsulation we can achieve abstraction in java.
How to achieve encapsulation in Java?
As shown in the below example class Student is an example of encapsulated class. To set and get the values for name and age outside the class, we have a public getter and setter method.
Advantages of Encapsulation in java
1. Data hiding:
- We can write our own implementation logic in our getter setter method and while setting the value we can validate any condition before assigning or returning the value of a variable.
- This logic is hidden from the user calling getter or setter method.
- In Student class if we want to add a condition on age then we can add an extra check on setter as shown below.
2. Loose Coupling:
- We can change the variable name (without changing the getter-setter methods) and this will not affect the user since the user is accessing methods instead of variables directly.
- In the above example, if we change the variable student name into other then we can update our code as follows.
3. Access Control:
- If you don’t want to provide access to any variable outside of the class. Keep that variable private and don’t create getter and setter methods.
- If want to give read-only access then just create a public getter method without any setter method.
- If want to give write access then just create a public setter method without any getter.
Hence by creating a getter or setter we can control access to the variable outside of the class.
What is the difference between Encapsulation and Abstraction?
- Abstraction is implemented using Interface and Abstract class whereas encapsulation is implemented using private and protected access modifiers.
- Abstraction is hiding the secure data and providing the data which is not meant to be secure, whereas encapsulation is data hiding into a single unit to restrict access from outside of the class.
- An example for abstraction is the ATM machine and an example for Encapsulation is medical capsules.