Link to home
Start Free TrialLog in
Avatar of esotericlete
esotericlete

asked on

Returning an object in a Vector.

I have the following definition of a class:


class Bank {
     private Vector accounts;

     Bank() { // Constructor
          accounts = new Vector();
     }

     public void addAccount(BankAccount newAccount) {
          accounts.add(newAccount);
     }

     public BankAccount getAccount(int index) {

     return (accounts.get(index));

         
     }

A class named "BankAccount" has already been defined, containing a few Strings and Doubles. However, I want Bank.getAccount to return a BankAccount class when it is called, as I have attempted to do so above. However, the statement "return (accounts.get(index));" states that there is an "Incompatible type" error.

I know that the get() method returns an Object, but isn't the getAccount() method already defined as returning an Object? What am I doing wrong?

If you need more information, please let me know.
ASKER CERTIFIED SOLUTION
Avatar of yoren
yoren

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of esotericlete
esotericlete

ASKER

Is this the case for every single method that returns an Object, but does not explicitly state what type of Object it returns?
Yes. The key here is that you're trying to return an Object in place of a BankAccount. Every BankAccount is an Object, but not every Object is a BankAccount. That's why you have to cast in this case.

If it were the reverse (returning a BankAccount instead of an Object), then it would be valid, since every BankAccount is  an Object:

public Object someMethod() {
  BankAccount acct = new BankAccount();
  return acct;
}