Access Specifiers and Encapsulation
The private, package-private, protected and public levels control which classes can use a member, and encapsulation keeps fields private behind methods that enforce the class's rules.
Protect an invariant by controlling which code can read or update a field.
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.