https://codegym.cc/groups/posts/113-introducing-the-externalizable-interface
I don't understand why the the following is said in the lecture (link above) :
"Third, when you use inheritance, all descendant classes that inherit some externalizable class must also have default constructors."
I assume this is only true if (although this was not written in the sentence) so if we want to serialize/deserialize these descendant classes as well?
I tried to add a child class written without a default constructor to an externalizable class that I serialized and didn't get any errors on deserialization, it worked fine:
import java.io.*;
public class Cat implements Externalizable {
// we want to serialize a Cat object. So this class must have a default constructor, and yes, it does.
public int age;
public void writeExternal(ObjectOutput oo) throws IOException {
oo.writeInt(age);
}
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException {
age = oi.readInt();
}
public static void main (String[] args) throws Exception {
Leopard leop = new Leopard(80);
leop.age = 12;
Cat c1 = new Cat (); // the object we want to serialize/deserialize
c1.age = 6;
System.out.println(c1.age);
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(c1);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Cat c2 = (Cat) ois.readObject();
System.out.println(c2.age);
}
}
class Leopard extends Cat { // a descendant class that inherits an externalizable class, and...
public int speed;
public Leopard (int s) { // and according to CG it should to have a default constructor, but it doesn't
speed = s;
}
}