Card 07/ 10

GotchaDifficulty: Intermediate1 min

Why Your Subclass Cannot See a private Field It Inherited

The subclass extends a class that has a balance field. The subclass has a balance — you can print it through a parent method — and referring to it by name will not compile.

text
SavingsAccount.java:6: error: balance has private access in Account
        balance += interest;
        ^

Every SavingsAccount object contains a balance. Inheritance put it there and nothing can take it out. What private controls is not whether the field exists but who may write its name, and private means one class and no other.

What a subclass can do with each kind of parent member
DeclaredExists in the objectSubclass may name it
privateYesNo
protectedYesYes
No modifier, same packageYesYes
publicYesYes

Go through the parent's own methods instead — deposit(interest) rather than balance += interest — because those methods are where the parent's rules about its field live. If no such method exists, the parent is missing one, and adding it is a smaller change than widening the field.