我是编程新手,一周前刚刚学习了继承,并且有一个关于如何设计扩展其他类的适当类的问题。下面的代码是将所有银行账户对象存储到ArrayList中的 Bank类,这就是我在 Bank 类中扩展类ArrayList的原因。
问题一:银行类属性为ArrayList。所以这就是我super()
在构造函数内部调用的原因。由于Bank类扩展了ArrayList,因此可以通过调用创建属性super()
,所以我认为bank中不需要其他私有属性,除了我通过调用创建的属性super()
。这是进行继承的正确方法吗?
问题2:由于没有属性,所以卡在通过ObjectOutputStream进行序列化。我想写 ArrayList(我super()
在构造函数中创建的属性),但不能,因为我不知道如何引用我在超级构造函数中创建的 ArrayList 属性。我尝试了 writeObject(this),但它显然不起作用。如何序列化ArrayList?
问题3:如果这是实现Bank类继承的正确方法,我如何从ObjectInputStream加载ArrayList?因为没有属性,所以我不知道如何引用我制作的属性super()
,所以我做了这样的事情
this = (ArrayList)ois.readObject()
但它没有用......当没有属性时,如何使用反序列化加载 ArrayList?
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
}
}