I have a class called Library that extends ArrayList. I did this because (I think) a true is-a relationship exists between the Library class and an ArrayList - a Library is simply a collection of books, plus a few methods.
One of those methods is load(), which deserializes a saved Library object. My question is: How do I make the deserialized object into the "active" instance of Library? I want to do something like this = load()
in the constructor of the library, since load()
returns a Library object. However, I get a compiler error cannot assign a value to final variable this
when I try to do it. What is the proper syntax to use for this purpose?
public class Library extends ArrayList<Book> implements Serializable{
public Library(){
load();
}
...
Library load() throws IOException, ClassNotFoundException {
File f = new File (System.getProperty("user.home")+"\\Documents\\CardCat\\library.ser");
ObjectInputStream ois = new ObjectInputStream (new FileInputStream (f));
Library lib = (Library)ois.readObject();
System.out.println("ran load sucessfully");
return lib;
}
EDIT: It seems that the universal consensus is that this is the wrong approach, and that I should instead create a Library class that doesn't extend ArrayList, but has an ArrayList instance variable. This is actually how I had it structured about an hour ago, but I thought that extending ArrayList might be a little simpler. My primary rationale for this was that the ArrayList was the only variable of the Library class, I refer to that ArrayList very frequently from other classes, and every time I did so I was having to call library.libList
, so I thought being able to refer simply to library
would be simpler. Looking back, and taking your input into consideration, it seems this this is a rather trivial benefit and it comes at the cost of a significant hit to performance.
Although I'd like to better understand what those costs are, am I understanding your thoughts correctly? I am (obviously, I'm sure) still learning and experimenting with all sorts of things, and very much appreciate any input that helps me identify failed experiments.