One of the most important features of object-oriented programming is encapsulation.
This feature allows us to isolate the data of our objects from the access of other external objects, and thus restrict direct access to the attributes or methods that we do not want to allow, since the state of an object is generally hidden.
To define visibility in Java, reserved words are available :
Allows access from any class to any method or attribute defined with this modifier.
Allows access only from the same class to the method or attribute marked with this modifier.
Allows access by the methods of the class, the methods of derived classes and classes belonging to the same package.
- Package or default
This level of protection is applied when none of the above three labels have been specified.
Advantages of encapsulation
- Data Hiding
The user will have no idea about the inner implementation of the class. It will not be visible to the user how the class is storing values in the variables. The user will only know that we are passing the values to a setter method and variables are getting initialized with that value.
- Increased Flexibility
We can make the variables of the class read-only or write-only depending of our requirement. If we wish to make the variables read-only then we have to omit the setter methods like setName(), setAge(), etc. from the above program or if we wish to make the variables as write-only then we have to omit the get methods like getName(), getAge(), etc. from the above program.
Encapsulation also improves the re-usability and is easy to change with new requirements.
- Testing code is easy
Encapsulated code is easy to test for unit testing.