Java Reference
In-Depth Information
private double balance; // Don't
}
Sure, now the deposit method compiles, but it doesn't update the correct
balance! Such a CheckingAccount object has two instance fields, both named
balance (see Figure 6 ). The getBalance method of the superclass retrieves
one of them, and the deposit method of the subclass updates the other.
Figure 6
Shadowing Instance Fields
C OMMON E RROR 10.3: Failing to Invoke the Superclass
Method
A common error in extending the functionality of a superclass method is to forget
the super . qualifier. For example, to withdraw money from a checking account,
update the transaction count and then withdraw the amount:
public void withdraw(double amount)
{
transactionCount++;
withdraw(amount);
// ErrorȌshould be super.withdraw(amount)
}
Here withdraw(amount) refers to the withdraw method applied to the
implicit parameter of the method. The implicit parameter is of type
CheckingAccount , and the CheckingAccount class has a withdraw
method, so that method is called. Of course, that calls the current method all over
again, which will call itself yet again, over and over, until the program runs out of
Search WWH ::




Custom Search