Java makes serializing objects easy. You can make any object whose class implements the java.io.Serializable interface persistent with only a few lines of code. Unlike implementing the ActionListener event-handling interface, for example, no extra methods need to be added to implement the interfacethe purpose of the interface is simply to identify which classes can be safely serialized and which cannot at runtime. You need only add the implements keyword to your class declaration to identify your classes as serializable, like so:
public class UserData implements java.io.Serializable
Once a class is serializable, you can write the object to any OutputStream, such as to disk. To achieve this, you must first create an instance of java.io.ObjectOutputStream and pass the constructor an existing OutputStream instance. You could use code like this:
// Use a FileOutputStream to send data to a file
// called myobject.data.
FileOutputStream f_out = new
// Use an ObjectOutputStream to send object data to the
// FileOutputStream for writing to disk.
ObjectOutputStream obj_out = new
// Pass our object to the ObjectOutputStream's
// writeObject() method to cause it to be written out
// to disk.
And that's it. In just three lines of code, you have written "myObject" (which you can consider just any arbitrary object) out to a disk file. Note that any Java object that implements the serializable interface, including those that are part of the Java standard class library, can be written to an output stream this way.
Furthermore, any objects that are referenced by a serialized object will also be stored, provided they also are serializable. This means that arrays, vectors, lists, and collections of objects can be saved in the same fashionwithout having to manually save each item individually. This can lead to significant time and code savings.
Think about it: if you have an object that contains other objects, you still can save the whole kit and caboodle to disk with no more code than the few lines above. It really can't get much easier than that!