I have a class named bankaccount. I have an array of Bankaccount objects 0-2 so 3 to be exact. Bankaccount is a super class. I have two other class Checking and Savings that extend from Bankaccount. I have two fields in Checking and savings. One is an ID and the other is the balance of that account thats supposed to correspond to that ID. I also have a main class called assignment 1. Heres my question. I was told yesterday that I could get the id of an account by checking the arrays like so arBankaccount[i].getId(); This doesnt work because the getter setter method of checking and savings are located in the checking and savings class not the superclass bankaccount. Im confused on how to get around this. I need to check through the arrays and find out which ID is located at what reference in the array. Inheritance is new to me so sorry if this question was very dumb.
-
Perhaps make BankAccount abstract and leave the getId/setId methods unimplemented. Or implement it directly in BankAccount. Or, worst case, you may create an interface like Identifiable that requires a getId() method and you could check that the elements of your array implement the interface before casting and calling getId()drobert– drobert2013-10-25 20:00:28 +00:00Commented Oct 25, 2013 at 20:00
Add a comment
|
2 Answers
If you have different implementation in Checking and Savings for the id (or perhaps in a latter subclass of BankAccount), you can make BankAccount an interface with the getId/setId methods and have the Checking/Savings implement that interface:
interface BankAccount
{
int getId();
void setId(int id);
}
class Checking implements BankAccount
{
int getId() { /* your implementation for Checking */ }
void setId(int id) { /* your implementation for Checking */ }
}
class Savings implements BankAccount
{
int getId() { /* your implementation for Savings */ }
void setId(int id) { /* your implementation for Savings */ }
}
Note: you do not need an implementation for getId/setId in BankAccount (just the signatures) as it is an interface: it only describes what methods its implementers have.
The advantage is that you can provide your own implementation of the methods regardless of the implementation of other classes.