Java Reference
In-Depth Information
S ELF C HECK
8. Why didn't the SavingsAccount constructor in Section 10.1 Call its
Superclass Constructor?
9. When you invoke a superclass method with the super keyword, does
the call have to be the first statement of the subclass method?
10.5 Converting Between Subclass and Superclass Types
It is often necessary to convert a subclass type to a superclass type. Occasionally, you
need to carry out the conversion in the opposite direction. This section discusses the
conversion rules.
Subclass references can be converted to superclass references.
The class SavingsAccount extends the class BankAccount . In other words, a
SavingsAccount object is a special case of a BankAccount object. Therefore, a
reference to a SavingsAccount object can be converted to a BankAccount
reference.
SavingsAccount collegeFund = new SavingsAccount(10);
BankAccount anAccount = collegeFund;
Furthermore, all references can be converted to the type Object .
Object anObject = collegeFund;
Now the three object references stored in collegeFund , anAccount , and
anObject all refer to the same object of type SavingsAccount (see Figure 7 ).
However, the object reference anAccount knows less than the full story about the
object to which it refers. Because anAccount is an object of type BankAccount ,
you can use the deposit and withdraw methods to change the balance of the
savings account. You cannot use the addInterest method, thoughȌit is not a
method of the BankAccount superclass:
452
453
anAccount.deposit(1000); // OK
anAccount.addInterest();
Search WWH ::




Custom Search