Card 03/ 08

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.

Who can reach a member at each of the four access levels
WrittenSame classSame packageSubclass elsewhereAnywhere
privateYesNoNoNo
nothing at allYesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
java
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.