"Hello, Amigo! I'd like to add a little to what Ellie told you."

Sometimes you need to control the serialization process. Here are some of reasons why:

1) An object is not ready for serialization: its current internal state is in the process of changing.

2) An object contains non-serializable objects, but can convert them into a form that can be easily serialized, e.g. save them as a byte array or something else.

3) An object wants to deserialize all its data as one unit and/or to encrypt it before serialization.

There are many reasons why you might want to perform serialization manually. But we don't want to lose all the advantages that standard serialization offers. After all, our object might use other objects. But they can't be serialized if our object doesn't support serialization.

This situation also has a solution: the Externalizable interface. We must thank Java's visionary creators. Simply replace the Serializable interface with the Externalizable interface, and your class can manage the serialization process manually.

The Externalizable interface has two methods, which the Serializable interface does not, that are called by the Java machine when an object is serialized. This is how it looks:

Code
class Cat implements Externalizable
{
 public String name;
 public int age;
 public int weight;

 public void writeExternal(ObjectOutput out)
 {
  out.writeObject(name);
  out.writeInt(age);
  out.writeInt(weight);
}

 public void readExternal(ObjectInput in)
 {
  name = (String) in.readObject();
  age = in.readInt();
  weight = in.readInt();
 }
}

Remind you of anything?

"Holy moly! This is exactly how we tried to save objects before we considered serialization."

"This makes everything simple: if standard serialization is adequate, we just inherit the Serializable interface. If it's not adequate, then we inherit Externalizable and write our own code to save/load our object."

"But is a class marked Externalizable considered serializable? Can we use such a class to "safely" store references to our serializable classes?"

"Yes. If a class implements Serializable or Externalizable, it is considered serializable."

"It's the perfect solution. I like it."

"I'm happy to hear that. But there's more to it... You should ask Professor Hans about all the nuances. They certainly exist. He wanted to give you something to read."