Data Encapsulation in Java

Encapsulation is a programming concept that refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components. It is one of the fundamental principles of object-oriented programming (OOP).

Here is an example of encapsulation in Java:

public class Employee {
   private String name;
   private String employeeId;
   private String ssn;
   private int salary;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getEmployeeId() {
      return employeeId;
   }

   public void setEmployeeId(String employeeId) {
      this.employeeId = employeeId;
   }

   public String getSsn() {
      return ssn;
   }

   public void setSsn(String ssn) {
      this.ssn = ssn;
   }

   public int getSalary() {
      return salary;
   }

   public void setSalary(int salary) {
      this.salary = salary;
   }
}

In the above example, the data members (name, employeeId, ssn, and salary) are private, which means they can only be accessed within the class. However, we can still access and modify these data members using the public setter and getter methods (setName(), getName(), setEmployeeId(), etc.). This is an example of encapsulation because the data is "encapsulated" within the class and can only be accessed through the methods provided.

Encapsulation helps to protect the data within an object from being accessed or modified by code outside of the object. It also allows us to change the implementation of the object's methods without affecting the code that uses the object, as long as we don't change the method signatures. This makes the code more maintainable and flexible.

Encapsulation is an important concept in OOP because it helps to achieve encapsulation and modularity, which are two of the four fundamental principles of OOP (the other two being inheritance and polymorphism).