Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Easy · Free

What is encapsulation? Why use private fields and getters/setters?

FresherFundamentalsOOP & Language Fundamentals
Model answer

Encapsulation

Encapsulation hides internal state behind a controlled API so invariants hold—balance never negative, email always validated.

java
class Account {
  private double balance;
  public void deposit(double amt) {
    if (amt <= 0) throw new IllegalArgumentException();
    balance += amt;
  }
  public double getBalance() { return balance; }
}
  • private fields + public methods = flexibility to change internals without breaking callers.
  • Getters/setters are not mandatory—prefer meaningful behavior methods (withdraw) over raw setters.
Link to security: don't expose mutable internals (return copies of collections).