Intermediate⏱️ 8 min📘 Topic 10 of 22

🔒 Encapsulation in Java — Access Modifiers and Getters/Setters

Master encapsulation in Java — private fields, public methods, getters and setters, and the four access modifiers (private, default, protected, public) with examples and interview Q&A.

Encapsulation = bundling data with the methods that operate on it, and hiding the internal state behind a controlled interface. The first pillar of OOP.

🔐 The four access modifiers

ModifierSame classSame packageSubclassAnywhere
private
default (none)
protected
public

🎯 The encapsulation recipe

  1. Make fields private.
  2. Provide public getters/setters to read/modify them.
  3. Add validation inside setters to protect invariants.
public class Account {
  private double balance;  // hidden
  public double getBalance() { return balance; }
  public void deposit(double amt) {
    if (amt <= 0) throw new IllegalArgumentException("positive only");
    balance += amt;  // validated
  }
}

💡 Why it matters

Callers can't put the object into an invalid state. You can change the internal representation later without breaking callers. This is the foundation of maintainable APIs.

💻 Code Examples

Validation in a setter protects the invariant

class Person {
  private int age;
  public void setAge(int age) {
    if (age < 0) throw new IllegalArgumentException("age >= 0");
    this.age = age;
  }
  public int getAge() { return age; }
}
Person p = new Person();
p.setAge(30);
System.out.println(p.getAge());
Output:
30

Access modifier visibility

public class Demo {
  private int secret = 1;      // only this class
  int packageVisible = 2;      // same package
  protected int forSubclass = 3;
  public int everyone = 4;
}
Output:
Compiles; visibility enforced at access sites.

⚠️ Common Mistakes

  • Making fields public 'for convenience' — destroys encapsulation and lets callers corrupt state.
  • Writing trivial getters/setters with no validation when an immutable object would be better.
  • Confusing default (package-private) with public — omitting a modifier is NOT public.
  • Overusing protected — it exposes internals to all subclasses and the whole package.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.What is encapsulation?Beginner
Bundling data (fields) with the methods that act on them and restricting direct access to the data. Achieved by making fields private and exposing controlled public methods (getters/setters).
Q2.What are the four access modifiers in Java?Beginner
private (same class only), default/package-private (same package), protected (package + subclasses), and public (everywhere). Default applies when no modifier is written.
Q3.What's the difference between default and protected access?Intermediate
Default (no modifier) is visible only within the same package. protected adds visibility to subclasses, even in other packages.
Q4.Why use getters and setters instead of public fields?Intermediate
They let you add validation, make fields read-only, change the internal representation without breaking callers, and add logging or lazy computation — none of which is possible with public fields.

🧠 Quick Summary

  • Encapsulation = private data + controlled public methods.
  • Four modifiers: private, default (package), protected, public.
  • Validate inside setters to protect invariants.
  • Default (no modifier) is package-private, NOT public.
  • Encapsulation enables changing internals without breaking callers.