Understanding Java Encapsulation

In Java, encapsulation is a concept that involves bundling the data (fields) and methods that operate on the data into a single unit known as a class. It restricts direct access to some of the object's components and can prevent unintended interference.

Example of Encapsulation:


// Example of encapsulation
public class Student {
  // Private fields
  private String name;
  private int age;

  // Public methods to access and modify the private fields
  public String getName() {
    return name;
  }

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    if (age >= 0) {
      this.age = age;
    } else {
      System.out.println("Invalid age. Age must be non-negative.");
    }
  }
}

Using Encapsulation:


// Create an object of the 'Student' class
Student student = new Student();

// Access and modify fields using public methods
student.setName("John Doe");
student.setAge(20);

// Retrieve and display information
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());

Note:

Encapsulation helps in organizing and securing the code by hiding the internal implementation details of a class. Private fields can only be accessed or modified through public methods, providing control over data integrity.