Encapsulation and invariants
What you will learn
Encapsulation means keeping the details of an object behind a controlled set of operations. An invariant is a rule that must hold whenever the object is ready for use, such as a stock quantity that never becomes negative. Private fields help enforce the rule, but the constructor and every operation that changes state must also preserve it.
After this lesson you can:
- Identify an invariant and the operations that can break it.
- Implement a controlled update that leaves the object unchanged on rejection.
Use a separate Main.java for each example. Compile with javac Main.java and run with java Main. The code is compatible with Java 21; Java 25 execution is not yet verified.
class Stock { private int quantity; Stock(int quantity) { if (quantity < 0) throw new IllegalArgumentException("negative stock"); this.quantity = quantity; } public int quantity() { return quantity; } public boolean reserve(int units) { if (units <= 0 || units > quantity) return false; quantity -= units; return true; }}public class Main { public static void main(String[] args) { Stock stock = new Stock(5); System.out.println(stock.reserve(3)); System.out.println(stock.quantity()); System.out.println(stock.reserve(4)); System.out.println(stock.quantity()); }}Expected output:
true2false2The first request leaves two units. The second request exceeds the available stock and does not change it.
Protect the rule, not just the field
A field is part of an object's representation. A public method is an operation that callers can use. In Stock, the constructor establishes quantity >= 0. reserve checks the request before subtracting. A false result means no units were reserved and the quantity remains unchanged. This design makes an invalid quantity hard to create through ordinary calls, rather than asking every caller to remember a separate validation rule.
A getter that returns an int copies the value. A setter is not mandatory: a method named reserve describes the business operation and can enforce its constraints. A private field with an unrestricted public setter is still vulnerable to invalid state. If multiple fields form one invariant, update them together only after all checks pass. These examples assume a single thread; privacy is not synchronization.
For ordinary top-level classes on the classpath, private members are restricted to their enclosing top-level class (including its nested classes), an omitted access modifier permits same-package access, protected also allows certain subclass access, and public permits access when the declaring type is accessible. Packages group related types and help establish access boundaries; a subpackage is a different package. Java modules can further limit access. We will explore subclass access in Chapter 11. The programs here use the unnamed package; save each as Main.java and compile and run with JDK 21 or compatible newer JDK.
class Capacity { private final int limit; private int used; Capacity(int limit) { if (limit < 0) throw new IllegalArgumentException("negative limit"); this.limit = limit; } public boolean add(int units) { if (units <= 0 || units > limit - used) return false; used += units; return true; } public int remaining() { return limit - used; }}public class Main { public static void main(String[] args) { Capacity room = new Capacity(10); System.out.println(room.add(10)); System.out.println(room.remaining()); System.out.println(room.add(Integer.MAX_VALUE)); System.out.println(room.remaining()); }}Expected output:
true0false0Check against remaining capacity before adding, so an oversized request cannot overflow the sum.
Check a boundary or variation
class Stock { private int quantity; Stock(int quantity) { if (quantity < 0) throw new IllegalArgumentException("negative stock"); this.quantity = quantity; } public int quantity() { return quantity; } public boolean reserve(int units) { if (units <= 0 || units > quantity) return false; quantity -= units; return true; }}public class Main { public static void main(String[] args) { Stock stock = new Stock(2); System.out.println(stock.reserve(0)); System.out.println(stock.reserve(-1)); System.out.println(stock.quantity()); }}Expected output:
falsefalse2Rejecting nonpositive requests prevents an accidental stock increase through subtraction of a negative number.
Common mistakes
Do not expose quantity as a public field or provide a setter that accepts any integer. Neither protects the invariant. For a beginner example, throwing IllegalArgumentException in the constructor means invalid construction stops; exception handling is taught in Chapter 12.
Practice
Create a Stock class with a private nonnegative quantity, a quantity() accessor and a reserve(int units) operation. Return false for nonpositive requests and requests above the available quantity. Verify normal, exact, and rejected reservations.
Validate the initial value in the constructor. Check both invalid conditions before subtracting.
Next: Composition and dependencies.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Encapsulation and invariants — knowledge check
Apply the stated Java 21-compatible contracts and predict observable behavior.
What is the stock invariant?
Stock starts at 5. reserve(7) returns what and leaves what?
Why reject reserve(-2)?
Why check units > limit - used before adding?
Can a private field with an unrestricted setter still violate an invariant?