Java Reference
In-Depth Information
Let's see how savings account objects are different from
BankAccount
objects. We
will set an interest rate in the constructor, and we need a method to apply that interest
periodically. That is, in addition to the three methods that can be applied to every
account, there is an additional method
addInterest
. The new method and instance
field must be defined in the subclass.
When defining a subclass, you specify added instance fields, added methods, and
changed or overridden methods.
public class SavingsAccount extends BankAccount
{
public SavingsAccount(double rate)
{
Constructor implementation
}
public void addInterest()
{
Method implementation
}
private double interestRate;
}
Figure 2
shows the layout of a
SavingsAccount
object. It inherits the
balance
instance field from the
BankAccount
superclass, and it gains one additional
instance field:
interestRate
.
Next, you need to implement the new
addInterest
method. The method computes
the interest due on the current balance and deposits that interest to the account.
Figure 2
Layout of a Subclass Object
440