Card 03/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
The Four Access Levels, and the One With No Keyword
Three keywords control who may reach a member, and there are four answers. The fourth is what you get by writing no keyword at all, and it is the one people are surprised by.
| Written | Same class | Same package | Subclass elsewhere | Anywhere |
|---|---|---|---|---|
private | Yes | No | No | No |
| nothing at all | Yes | Yes | No | No |
protected | Yes | Yes | Yes | No |
public | Yes | Yes | Yes | Yes |
class Account {
private long pence; // this class only
long lastAudit; // this package
protected String owner; // this package, plus subclasses anywhere
public String reference; // everyone
}The second row is often called "default" or "package-private", and neither name is a keyword. A field with no modifier is reachable by every class in the same package, which is wider than most people intend when they leave the word out.
Row three is wider than row two, not narrower: protected adds subclasses to package access rather than replacing it. A protected field is therefore reachable by anyone who writes a subclass, which is anyone at all.
Start every field at private and widen only when something concrete cannot be done otherwise. Widening later is a small change; narrowing later breaks whoever took you up on it.