previous | start | next

"Down casting"

Suppose we wish to add a half point to the interest rate for b[2].

We can't write
        BankAccount[] b = new BankAccount[3];

        double newRate = b[2].getRate() + 0.5;
        b[2].setRate( newRate);

We get errors at both b[2].getRate() and b[2].setRate because the
declared type of b[2] is BankAccount, not SavingsAccount.

    Any SavingsAccount is  a kind of BankAccount

but
    
    A BankAccount is not necessarily a SavingsAccount.

We can try a cast:

        ((SavingsAccount) b[2]).getRate() 

This is called a "downcast" because SavingsAccount is a
subclass of BankAccount and we are casting the type to a subtype.


              BankAccount
                  |
                  |
              SavingsAccount
   


previous | start | next