Encapsulation

What is Encapsulation?

Encapsulation means keeping an object's data private and exposing only safe operations. The object protects its own rules (invariants), for example "balance can never be negative".

Outside code  --->  public methods (deposit, withdraw, getBalance)  --->  private data (balance)
                    validation happens here                                 never touched directly

Getters and Setters with Validation

Example

The setter refuses invalid values, so an Employee can never have a negative salary or an empty name.

public class Main {
    public static void main(String[] args) {
        Employee e = new Employee("Ravi", 50000);
        e.setSalary(55000);
        System.out.println(e.getName() + " earns " + e.getSalary());
        try {
            e.setSalary(-10);
        } catch (IllegalArgumentException ex) {
            System.out.println("Error: " + ex.getMessage());
        }
        System.out.println("Salary still " + e.getSalary());
    }
}

class Employee {
    private final String name;
    private double salary;

    Employee(String name, double salary) {
        if (name == null || name.isBlank()) throw new IllegalArgumentException("name required");
        this.name = name;
        setSalary(salary);
    }

    public String getName() { return name; }

    public double getSalary() { return salary; }

    public void setSalary(double salary) {
        if (salary < 0) throw new IllegalArgumentException("salary cannot be negative");
        this.salary = salary;
    }
}

Output

Ravi earns 55000.0
Error: salary cannot be negative
Salary still 55000.0

Benefits

  • Control: validation in one place instead of everywhere the field is used.
  • Flexibility: you can change how data is stored without breaking callers.
  • Read-only fields: provide only a getter (and make the field final).
  • Security: sensitive data (PIN, password hash) is never exposed.

Note: Do not generate a setter for every field by habit. Add a setter only when the value is allowed to change.