Converting Between Subclass and Superclass Types
Ok to convert subclass reference to superclass reference
SavingsAccount collegeFund = new SavingsAccount(10);
BankAccount anAccount = collegeFund;
Object anObject = collegeFund;
The three object
references stored in
collegeFund,
anAccount,
and
anObject
all refer to the same object of type
SavingsAccount
Superclass references don't know the full story:
anAccount.deposit(1000); // OK
anAccount.addInterest();
// No--not a method of the class to which anAccount belongs
When you convert between a subclass object to its superclass type:
The value of the reference stays the same – it is the memory location of the object
But, less information is known about the object
Why would anyone want to know less about an object?
Reuse code that knows about the
superclass
but not the
subclass:
public void transfer(double amount, BankAccount other)
{
withdraw(amount);
other.deposit(amount);
}
Can be used to transfer money from any type of BankAccount
Occasionally you need to convert from a superclass reference to a subclass reference
BankAccount anAccount = (BankAccount) anObject;
This cast is dangerous: if you are wrong, an exception is thrown
Solution: use the instanceof operator
instanceof: tests whether an object belongs to a particular type
if (anObject instanceof BankAccount)
{
BankAccount anAccount = (BankAccount) anObject;
. . .
}
Why did the second parameter of the transfer method have to be of type BankAccount and not, for example, SavingsAccount?
Answer:
We want to use the method for all kinds of bank accounts. Had we used a
parameter of type
SavingsAccount,
we couldn't have called the method with a
CheckingAccount
object.
Why can't we change the second parameter of the transfer method to the type Object?
Answer: We cannot invoke the deposit method on a variable of type Object.