Java Reference
In-Depth Information
ȗ
withdraw(double amount)
(overrides
BankAccount
method)
ȗ
deductFees()
(new to
CheckingAccount
)
Next, let us implement these methods. The
deposit
method increments the
transaction count and deposits the money:
public class CheckingAccount extends BankAccount
{
public void deposit(double amount)
{
transactionCount++;
//
Now add
amount to balance
. . .
}
. . .
}
Now we have a problem. We can't simply add
amount
to
balance
:
public class CheckingAccount extends BankAccount
{
public void deposit(double amount)
{
transactionCount++;
//
Now add
amount to balance
balance = balance + amount; // Error
}
. . .
}
Although every
CheckingAccount
object has a
balance
instance field, that
instance field is private to the superclass
BankAccount
. Subclass methods have no
more access rights to the private data of the superclass than any other methods. If you
want to modify a private superclass field, you must use a public method of the
superclass.
A subclass has no access to private fields of its superclass.
How can we add the deposit amount to the balance, using the public interface of the
BankAccount
class? There is a perfectly good method for that purposeȌnamely,