What does Serializable mean?
What exactly does it mean for a class to be Serializable
in Java? Or in general, for that matter...
Solution 1:
Serialization is persisting an object from memory to a sequence of bits, for instance for saving onto the disk. Deserialization is the opposite - reading data from the disk to hydrate/create an object.
In the context of your question, it is an interface that if implemented in a class, this class can automatically be serialized and deserialized by different serializers.
Solution 2:
Though most of the users have already given the answer, but I would like to add an example for those who need it in order to explain the idea:
Let's say you have a class person like the following:
public class Person implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String firstName;
public String lastName;
public int age;
public String address;
public void play() {
System.out.println(String.format(
"If I win, send me the trophy to this address: %s", address));
}
@Override
public String toString() {
return String.format(".....Person......\nFirst Name = %s\nLast Name = %s", firstName, lastName);
}
}
and then you create an object like this:
Person william = new Person();
william.firstName = "William";
william.lastName = "Kinaan";
william.age = 26;
william.address = "Lisbon, Portugal";
You can serialise that object to many streams. I will do that to two streams:
Serialization to standard output:
public static void serializeToStandardOutput(Person person)
throws IOException {
OutputStream outStream = System.out;
ObjectOutputStream stdObjectOut = new ObjectOutputStream(outStream);
stdObjectOut.writeObject(person);
stdObjectOut.close();
outStream.close();
}
Serialization to a file:
public static void serializeToFile(Person person) throws IOException {
OutputStream outStream = new FileOutputStream("person.ser");
ObjectOutputStream fileObjectOut = new ObjectOutputStream(outStream);
fileObjectOut.writeObject(person);
fileObjectOut.close();
outStream.close();
}
Then:
Deserialize from file:
public static void deserializeFromFile() throws IOException,
ClassNotFoundException {
InputStream inStream = new FileInputStream("person.ser");
ObjectInputStream fileObjectIn = new ObjectInputStream(inStream);
Person person = (Person) fileObjectIn.readObject();
System.out.println(person);
fileObjectIn.close();
inStream.close();
}
Solution 3:
It means that instances of the class can be turned into a byte-stream (for example, to be saved to a file) and then converted back into classes again. This reloading could happen in a different instance of the program, or even on a different machine. Serialisation (in any language) involves all sorts of issues, though, especially when you've got references to other objects inside the serialisable one.