Start With the Problem#
StudyBuddy's quizzes have three kinds of question:
multiple choice — correct if the student picks option A;
true/false — correct if the student says
false;short answer — correct if the student types "water", ignoring case and spaces.
They share a lot (every question has text and points, and can be graded) but differ in exactly one thing: how to check an answer. Without OOP you'd write:
if (type.equals("mcq")) { ... } else if (type.equals("tf")) { ... } else if (type.equals("short")) { ... }— copied into the grading code, the display code, the export code… Add a fourth type ("fill in the blank") and you must find and edit every copy. Miss one and it breaks.
And there's a second problem: StudyBuddy has an AI-credit balance per student. Right now any code anywhere can write
account.credits = -500;. Nothing protects the rule "credits can never go negative".
Object-oriented programming is the set of ideas that solves both: bundle data with the rules that protect it, and let different kinds of things share one interface while each behaves in its own way.
The Plain Picture#
An ATM. You can't open it and take money out of the drawer. You can only use its buttons: check balance, withdraw. The ATM checks every request — "is the amount positive? is there enough money?" — before touching the cash inside. The drawer is hidden; the buttons are the only way in.
The Real Names#
Encapsulation = keeping an object's data private and allowing access only through methods that enforce its rules.
The rules that must always be true about an object are its invariants — e.g. "credits ≥ 0".
Access modifiers control who can see a field, method or class:
| Modifier | Visible to | Typical use |
|---|---|---|
private | only code inside the same class | fields (almost always) |
| (none) — "package-private" | classes in the same package | helpers internal to a package |
protected | same package and subclasses (Ch 2) | things subclasses need |
public | everyone | the object's intended "buttons" |
Under the Hood#
class Account {
private int credits; // hidden: nobody outside can touch it
Account(int credits) {
if (credits < 0) throw new IllegalArgumentException("credits must be >= 0"); // guard the invariant from the start
this.credits = credits;
}
int getCredits() {
// a GETTER: read access only
return credits;
}
boolean spend(int amount) {
// the only way to change credits — with rules
if (amount <= 0 || amount > credits) return false;
credits -= amount;
return true;
}
}Account acc = new Account(10);
System.out.println(acc.spend(4) + " " + acc.spend(100) + " " + acc.getCredits()); // true false 6
new Account(-5); // rejected: credits must be >= 0
acc.credits = 5; // compile error: credits has private access in Account(throw new IllegalArgumentException(...) stops the constructor with an error — exceptions are taught in
Exceptions and Generics.)
Why this matters: because credits can only change through spend, the rule "never negative" is checked in one place and is
always true. If the rule changes ("allow a small overdraft for premium students"), you edit one method.
Getters and setters: a getter returns a field (getCredits); a setter changes one (setName). Don't generate a setter for
every field automatically — that throws encapsulation away. Offer meaningful operations (spend, refund) instead of raw setters.
Check yourself
4 questionsWhat is encapsulation, in one sentence?
Show answerHide answer
Hiding an object's data and exposing only methods that enforce its rules.
What's an invariant? Give one for StudyBuddy.
Show answerHide answer
A rule that must always hold for the object — e.g. "credits are never negative".
Order the four access levels from most to least restrictive.
Show answerHide answer
private → package-private → protected → public.
Why is spend(int amount) better than setCredits(int c)?
Show answerHide answer
spend enforces the business rules in one place; a setter lets callers put the object into any state, including invalid ones.