Card 07/ 10
All 10 cards
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.
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.
| Declared | Exists in the object | Subclass may name it |
|---|---|---|
private | Yes | No |
protected | Yes | Yes |
| No modifier, same package | Yes | Yes |
public | Yes | Yes |
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.