I'm new to programming and I just learned inheritance a week ago, and have a question for how to design proper class that extends other class. Code below is the Bank Class that stored all the bank account object into ArrayList, which is why I'm extending the class ArrayList in Bank class.
Question 1: Bank class attribute is ArrayList. So that is why I'm calling super()
inside of the constructor. Since attribute can created by calling super()
because the Bank class extends ArrayList, I thought that no other private attribute is needed in bank, besides the attribute that I created by calling super()
. Is this proper way to do inheritance?
Question 2: Since there is no attribute, I am stuck on serialization through ObjectOuputStream. I want to write ArrayList(attribute that I created by doing super()
in constructor), but can't because I don't know how to refer to the ArrayList attribute that I created in super constructor. i tried writeObject(this), but it did't work obviously. How can serialize ArrayList?
Question 3: If this is a right way to implements inheritance of Bank class, how can I load ArrayList from ObjectInputStream? Because there is no attribute, I don't know how to refer to the attribute that I make in super()
, so I did such a thing like
this = (ArrayList)ois.readObject()
But it didn't work... How can I load ArrayList using deserialization when there is no attribute?
public class Bank extends ArrayList<Account> implements Serializable{
//no attribute
public Bank(){
super();
}
//other methods...
public void saveToBinary() throws IOException{
FileOutputStream fos = new FileOutputStream("Bank_Account_Inherit_Binary.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this);//can't do this
oos.flush();
oos.close();
}
public void loadFromBinary() throws IOException, ClassNotFoundException{
FileInputStream fis = new FileInputStream("Bank_Account_Inherit_Binary.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
this = (ArrayList<Account>)object;//not working b/c "this" is final variable
}
}