Reputation: 27
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.
Upvotes: 0
Views: 328
Reputation: 3634
Psuedo code, untested and off the top of my head
class BankAccount{
private long id;
public long getId(){ //blah}
public void setId( long id) {// blah}
}
class Checking extends BankAccount {
}
class Savings extends BankAccount {
}
Now bankAccount[i].getId(0)
will work.
Upvotes: 2
Reputation: 28762
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.
Upvotes: 0