When an object is serializable, you can write its state outside the JVM. You might store it to a file, or send it out through a socket. Another JVM (or the same JVM at another time) can read back the state to create a clone of the original object.
Static fields aren't written, and neither are transient ones. In fact, the "transient" keyword means "don't write this field during serialization".
Primitive data is written out pretty much the way you'd expect. Object reference fields are written the way you'd hope: the referenced object is itself serialized and writtn out, and on the other end you get the right result: two objects for the price of one, with the reference in the "top level" object pointing to the second object. And so on, recursively, if the second object contains its own references to still other objects. Watch out for NotSerializableException if some object in the hierarchy doesn't implement Serializable.
There are some low-level infrastructure details, but that should get you started. More in Chapter 9 of "Complete Java 2 Certification".
There's a certain amou
Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
Joined: Feb 10, 2005
And what is the actual need to be used in practice and when?
Alexander asked, "And what is the actual need to be used in practice and when?"
Yeah, always a good question!
Suppose you're writing a painting program. Your data model is a vector that contains a bunch of PaintedThingDescriptor instances. PaintedThingDescriptor contains information about color, location, paint extur, etc. What happens when the user clicks "Save"? Without serialization you have to invent a file format - a contract with yourself concerning exactly how all that color, location, etc info gets stored. Then for 3 weeks life is a debugging nightmare because your file reading code has to exactly match what your file writing code did, and thorough testing is hard.
With serialization, you just call writeObject(theDataModelVector), and everything is taken care of for you. Same when you read back.
In addition to this kind of benefit, serialization is the lifeblood of RMI, JDBC, EJBs, and so on. In the simplest case, imagine an RMI call where a program on machine A invokes a method on an object on machine B. The arguments have to get shipped from A to B, and the return value has to come back from B to A. If any of those are objects, they are serialized.