1.) Why does this program work without the no-args constructor?
I read somewhere that if you write readObject and writeObject methods in a descendant class, you need a no-args constructor in the parent class.
Elsewhere I read that if you want to serialize a (serializable) class whose parent is not serializable, then the parent must have a no-arguments constructor.
The way the shared program works proves that neither statement is true.
Ultimately then, what is the correct statement, in what cases is a no-args constructor required? Because sometimes you really need it, prg won't work without it. But unfortunately I could not come to any conclusion when it is needed and when it is not.
2.) The output of the shared prg is this:
A1, A2, B1, B2
null, null, B1, B2
Question: why does it not load the nameA1 and nameA2 fields of the object?
Thanks in advance!:)
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(arrayOutputStream);
B b1 = new B();
b1.nameA1="A1";
b1.nameA2="A2";
b1.nameB1="B1";
b1.nameB2="B2";
System.out.println(b1.nameA1 + ", " + b1.nameA2+", " + b1.nameB1+", " + b1.nameB2);
oos.writeObject(b1);
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());
ObjectInputStream ois = new ObjectInputStream(arrayInputStream);
B b2 = (B) ois.readObject();
System.out.println(b2.nameA1 + ", " + b2.nameA2+", " + b2.nameB1+", " + b2.nameB2);
}
public static class A {
public String nameA1;
public String nameA2;
// public A() {
// }
}
public static class B extends A implements Serializable {
public String nameB1;
public String nameB2;
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
}