Card 03/ 08
Java Access Modifiers: private, Package-Private, protected and public
Three keywords, four answers, and the fourth is what you get by writing nothing.
Java has four access levels, which decide which code may refer to a field or method by name: private (this class), no keyword at all (this package), protected (this package plus subclasses anywhere) and public (everyone). Each is wider than the one before.
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 can be named 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.
← → move through sections and cards