Java Reference
In-Depth Information
What happens if you define a new field with the same name as a superclass field? For
example, can you define another field named balance in the SavingsAccount
class? This is legal but extremely undesirable. Each SavingsAccount object
would have two instance fields of the same name. The two fields can hold different
values, which is likely to lead to confusionȌsee Common Error 10.2 .
We already implemented the BankAccount and SavingsAccount classes. Now
we will implement the subclass CheckingAccount so that you can see in detail
how methods and instance fields are inherited. Recall that the BankAccount class
has three methods and one instance field:
public class BankAccount
{
public double getBalance() { . . . }
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
private double balance;
}
The CheckingAccount class has an added method deductFees and an added
instance field transactionCount , and it overrides the deposit and
withdraw methods to increment the transaction count:
public class CheckingAccount extends BankAccount
{
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
public void deductFees() { . . . }
private int transactionCount;
}
Each object of class CheckingAccount has two instance fields:
ȗ balance (inherited from BankAccount )
ȗ transactionCount (new to CheckingAccount )
446
447
You can apply four methods to CheckingAccount objects:
ȗ getBalance() (inherited from BankAccount )
ȗ deposit(double amount) (overrides BankAccount method)
Search WWH ::




Custom Search