Why serialization isn't default for all classes?and also why doesn't class Object implement Serializable,and all sub classes will be automatically Serializable.
I HAD THE SAME QUESTION!
I will quote from HF Java....
Q: "If serializable is so important, why isn't it the default for all classes? Why doesn't class Object implement Serializable, and then all subclasses will be automatically Serializable?"
A: "Even though most classes will, and should, implement serializable, you always have a choice. And you must make a conscious decision on a class by class basis, for each class you design, to 'enable' serialization by implementing serializable.
First of all, if serializarion were the default, how would you turn it off? Interfaces indicate a functionality, not a lack of functionality, so the model of polymorphism wouldn't work correctly if you had to say 'Implements NonSerializable' to tell the world that you cannot be saved."
Hope that helps....
When you do things right, people won't be sure you've done anything at all.
Some classes are simply not useful to be serialized. Like classes that represent data that is too related with a specific runtime context: Threads, Streams, etc. Even if you saved them and then restored them again in the same VM their data (and internal memory references) would be useless since the whole runtime context changes on every run.
John, what don't you agree with? My wanting to pack everything up for next time, or the HFJ quote?
I think there could hardly be anything more useful than to be able to pack up all your objects and variables... only to pull them out at a later date. All that time wasted on initializing and setting values, et cetera.... SAVED by packing things up in a nice little file.
Other than the runtime contexts as Francisco so kindly rained on my parade with, to be able to just come back to objects later (or even in another application!) makes my day sunny.
Joined: Sep 30, 2009
Don´t get me wrong but ruining people´s sunny days is something I´d hate doing. :-)
I must admit that, while it is a nice and very tempting idea to keep objects packed up in one, or several, files I think i should play Devil´s advocate one more time.
Imagine that you have all your objects already serialized. Now, you feel the need to change your objects a little bit: adding an extra int instance variable here and there, adding static variables or removing some. Change happens. .
When you get this scenario, everything you had on file cannot be deserialized back into objects again because their definition has changed! You would, most probably, have to recreate your whole set of files with serialized objects everytime you make even the slightest change to their definition (which defeats the whole point of serializing them).