Skip to content
Ameen Abozaid
BEG-021

Encapsulation

  • 6 Lessons
  • 68 min of reading
  • 3 h practice (estimate)
On this page 8 topics

Overview

Topics

  • Access modifiers
  • getters/setters
  • invariants
  • immutability

Learn first

68 min of reading · 3 h of practice (estimate)

Learning outcomes

  1. Apply private, package-private, protected, and public correctly.
  2. Protect invariants (e.g., balance never negative) inside the class, not in its callers.
  3. Decide when a getter or setter is appropriate and when a behavior method is better.
  4. Create an immutable class (final fields, no setters, defensive copies).

Lessons

  1. 01Why hide data11 min read
  2. 02Access modifiers11 min read
  3. 03Invariants: rules the object guarantees11 min read
  4. 04Getters, setters, and "tell, don't ask"12 min read
  5. 05Immutable objects12 min read
  6. 06Demo: protecting the balance invariant11 min read

Lab and exercises

Lab

BEG-021-LAB1 · Bank Accounts v2

Outcomes: 1, 2, 3, 4 · Time: ~2 h Make the fields of Account private. Enforce invariants (balance never negative, amounts positive) in the constructor and withdraw. Replace setBalance with behavior methods. Add an immutable Money class (final fields, no setters). Acceptance: no way to reach an invalid state from outside the class.

Exercises (assessment: code review exercise)

IDOutcomeTask
BEG-021-EX011Which of private, package-private, protected, public would you use for: a helper method, a field, a service method called from other packages, a method meant for subclasses?
BEG-021-EX022Add the rule "age is between 0 and 150" to a Person class so it cannot be broken.
BEG-021-EX033Rewrite if (c.getItems() > 0) c.setItems(c.getItems() - 1); as a behavior method.
BEG-021-EX044Make Money fully immutable and add plus.
BEG-021-EX054Fix a Team class that returns its internal List<String> members directly.
BEG-021-EX061, 2, 3, 4Code review: in a provided class, list every encapsulation violation and how to fix it.
Show solutions
  • EX01 private; private; public; protected.
  • EX02 Private field; check in the constructor and the setter (if any) and throw IllegalArgumentException when out of range.
  • EX03 public void removeItem() { if (items == 0) throw new IllegalStateException(); items--; } then c.removeItem();.
  • EX04 public final class Money { private final long cents; ... public Money plus(Money o) { return new Money(cents + o.cents); } }.
  • EX05 Return List.copyOf(members) (or an unmodifiable view), and copy any incoming list in the constructor.
  • EX06 Typical findings: public fields, a setter that skips validation, reflex getters/setters, returned mutable collection, missing constructor validation. Graded against the review checklist.

Quiz

Outcomes: O1 access modifiers · O2 invariants · O3 getters/setters vs behavior · O4 immutability.

A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.

  1. 1Visible only inside its own class:O1
  2. 2The default access (no modifier) is:O1
  3. 3protected allows access from:O1
  4. 4An invariant is:O2
  5. 5Where should "balance never negative" be enforced?O2
  6. 6On invalid input a method should:O2
  7. 7The best replacement for setBalance is:O3
  8. 8"Tell, don't ask" means:O3
  9. 9An immutable class has:O4
  10. 10A defensive copy is needed when a field:O4

Practical part

Code review exercise BEG-021-EX06 plus EX01 to EX05 and Bank Accounts v2. Pass: review finds at least four of the planted violations and the lab meets its acceptance.

Common mistakes

Generating getters/setters for every field by reflex; returning internal mutable arrays.

Assessment

Code review exercise: find encapsulation violations in a provided class.

Career relevance

Value objects (MID-060) and safe APIs (JNR-020).

Type to search levels, phases, modules and lessons.