ATHENA
Java Programming Essentials / Smart Reader
THE ATHENA LIBRARY

Java Programming Essentials

Miriam Okafor · textbook

Chapter 6 · Encapsulation and Access

Guarding the invariants

Declaring a field private means only the class itself may read or change it. Rather than exposing balance directly, an Account offers deposit() and withdraw() methods, each of which checks that the balance never becomes negative.

This is encapsulation: the class protects its own invariants. Callers depend on the public methods, not on internal details, so the implementation can change — perhaps storing cents as a long instead of a double — without breaking any other code.

Getters and setters are not encapsulation by themselves. A setter that accepts any value simply moves the problem. Good encapsulation exposes intentions such as withdraw(amount) instead of raw state.

Fictional educational sample written for the Athena demo · Page 118 of 412.

50%saved