Encapsulation

Encapsulation means bundling an object's data (fields) together with the methods that operate on that data, and hiding the internal state from direct access by outside code. Instead of letting other classes reach in and change a field directly, you make the field private and expose controlled access through public methods.

Why Hide the Data?

BenefitWhat it means
ValidationA setter can reject bad values before they're ever stored — e.g. refusing a negative age
FlexibilityYou can change how a value is stored or calculated internally without breaking any code that calls the getter/setter
ControlYou decide exactly what outside code is allowed to read or modify — some fields can even be read-only

Private Fields, Public Getters and Setters

The standard pattern: declare fields as private so they can't be touched directly from outside the class, then provide public methods — conventionally named getX() and setX() — to read and update them.

Example: A Person Class with Validation

public class Person {
  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(String newName) {
    name = newName;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int newAge) {
    if (newAge < 0) {
      throw new IllegalArgumentException("Age cannot be negative");
    }
    age = newAge;
  }
}

What's happening:

  • name and age are private — no other class can write person.age = -5; directly, it simply won't compile.
  • getAge() and getName() allow read access, while setAge() and setName() allow controlled writes.
  • setAge() validates the input and throws an exception for a negative value — bad data never gets a chance to corrupt the object's state.

Using the Class

Person p = new Person();
p.setName("Sonu");
p.setAge(28);

System.out.println(p.getName() + " is " + p.getAge() + " years old");

p.setAge(-5); // throws IllegalArgumentException
          
Note: Nothing outside Person can ever set age to an invalid value, because the only way in is through setAge(), and that method enforces the rule every single time.
Next up: dig into Abstraction — a related but different idea about hiding complexity rather than hiding data.