Encapsulation Program in Java

Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is made up of different varieties of medicine mixed together. Encapsulation acts as the protective barrier that stops the outside code to directly access the data (fields) of a Java class. The common way to achieve encapsulation is to declare fields of a class as private and exposing only the methods of that class to the outside world in order to access the fields. Consider the following example.

FileName: EcapsulationExample.java

Output:

Explanation: All the fields of the class Employee have been encapsulated. Thus, direct access of the fields i.e., emp.empAge, emp.empName, or emp.empId leads to the compilation error. Therefore, we need the public methods(getEmpName(), setEmpName(), setEmpAge(), and getEmpId() etc.) to access or manipulate the values of the private fields of the class employee.

Importance of Encapsulation

  • Encapsulation helps in data hiding. In the above example, the outer world has no idea how the age, name, and employee id of an employee is getting stored. One can never see the implementation of it since the fields are private.
  • Encapsulation enhances flexibility. In the above example, we can make the fields write-only or read-only based on the requirement. If we comment out the setter methods (setEmpName(), setEmpId(), setEmpAge()) then, we can only access the value of the fields but can not change it (read-only). If we comment out the code of getter methods (getEmpName(), getEmpId(), getEmpAge()) we find that we can manipulate values of the fields but can not access it (write-only).

Pin It on Pinterest

Share This