Access Specifiers and Encapsulation
A new developer at Brew Bar writes order.cups = -3; in the refund screen, and the day's takings go negative. Nothing stopped them, because the field was open to every class. Access specifiers let a class decide who may touch what, so its rules cannot be skipped.
The rule
Make fields private; open only the doors you mean to.
Java has four levels of access, from tightest to widest:
| Keyword | Who can use it |
|---|---|
private |
only code inside the same class |
| (no keyword) | any class in the same package |
protected |
the same package, plus subclasses elsewhere |
public |
every class, everywhere |
A package is a named folder of related classes, declared on the first line of each file, such as package com.brewbar.orders;. Classes in other packages bring it in with import com.brewbar.orders.Order;. Packages both organise code and set the boundary for the no-keyword level, called package-private.
Encapsulation means hiding an object's fields and exposing only methods that keep its rules:
package com.brewbar.orders;
public class Order {
private int cups = 1;
public int getCups() {
return cups;
}
public void addCups(int extra) {
if (extra < 1) {
throw new IllegalArgumentException("extra must be at least 1");
}
cups += extra;
}
}Now the only way to change cups is through addCups, which refuses bad input. The rule "cups is always at least 1" lives in one place and cannot be bypassed. You can later change how cups are stored without breaking any caller, because callers only ever saw the methods.
Getters (getCups) are common, but do not add a setter for every field by reflex. A public setCups(int) that accepts anything would reopen the door you just closed.
The shortcut
For every member, ask "Who truly needs this?" and pick the narrowest answer: only this class → private; its package → no keyword; subclasses → protected; the whole world → public. Start private and widen only when a real caller needs it.
The data
cupsis only changed by Order's own rules, so it becomesprivate.
Drills
Answer fast — trust the rule.
Which specifier lets only code inside the same class use a member?
A method in Order has no access keyword. Which other classes can call it?
cups is private in Order. Another class writes order.cups = -3;. What happens?
What is the main benefit of routing changes through addCups instead of a public field?
Remember
- Make fields private; open only the doors you mean to.
- Ask "who truly needs this?" and pick the narrowest level.
- Traps: public fields, and a setter for everything that undoes the protection.
