Java Encapsulation

Encapsulation means wrapping an object's data safely inside the class and controlling access to it through methods. It is one of the core ideas of object-oriented programming, and it keeps your data from being changed in careless or invalid ways.

The idea behind encapsulation

The recipe for encapsulation is simple: mark your fields as private so outside code cannot touch them directly, then provide public methods that read and update those fields. These methods are traditionally called getters and setters. Because every change now flows through a method, you get a single place to add validation.

  • Declare the fields private.
  • Add a public getter method to return each field's value.
  • Add a public setter method to change each field's value.
  • Put any validation rules inside the setter.

A class with getters and setters

public class Person {
  private String name; // hidden from outside code

  // Getter: lets others read the name
  public String getName() {
    return name;
  }

  // Setter: lets others change the name
  public void setName(String newName) {
    this.name = newName;
  }
}

Because outside code can no longer reach the field directly, the setter becomes the perfect spot to reject bad values. In the example below, the class refuses to store a negative age.

Protecting data with validation

public class Player {
  private int score;

  public int getScore() {
    return score;
  }

  public void setScore(int score) {
    if (score >= 0) {   // only accept valid values
      this.score = score;
    } else {
      System.out.println("Score cannot be negative.");
    }
  }

  public static void main(String[] args) {
    Player p = new Player();
    p.setScore(50);
    p.setScore(-10); // rejected
    System.out.println(p.getScore()); // Outputs 50
  }
}
Note: Trying to write p.score = 50 directly would cause a compile error, because score is private. Callers must go through setScore, which is exactly the point of encapsulation.
BenefitWhy it matters
Data protectionFields cannot be set to invalid values from outside.
ControlEvery read and write can be checked or logged in one place.
FlexibilityYou can change how a field is stored without breaking other code.
Read-only or write-onlyOmit a setter or getter to restrict access as needed.
Note: If you want a value that can be read but never changed after creation, provide a getter and leave out the setter. This creates a read-only property.

Exercise: Java Encapsulation

What is the core idea of encapsulation in Java?