Card 07/ 10
Why a Subclass Cannot Name a private Parent Field
The subclass has a balance, prints it through a parent method, and cannot write its name.
A private field declared in a parent is part of every subclass object, but only the parent's own code may refer to it by name. A subclass reaches it through the parent's methods, which is where the parent's rules about that field live.
The subclass extends a class that has a balance field. The subclass has a balance, which you can print 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, the extends relationship, 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. If no such method exists, the parent is missing one, and adding it is a smaller change than widening the field.
← → move through sections and cards