I understand this question can sound quite weird, but I wonder why the java.io.Serializable
interface has been implemented precisely as an interface, and not as a class?
What made me think about that point, is that we're talking about overriding the readObject
/writeObject
methods, while by definition, we don't override them (i.e. there's no super type of our Serializable
objects that already implement these methods).
Thus, if Serializable
would have been a class, it could have implemented the default readObject
/writeObject
methods, and the exenting classes could then have been able to really override the said methods.
Here is a not working workaround that illustrates my words:
public class Serializable implements java.io.Serializable {
private static final long serialVersionUID = 356223041512972356L;
protected void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
protected void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
}
}
public class MyClass extends Serializable {
private static final long serialVersionUID = -5437634103734137046L;
@Override
protected void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
super.readObject(stream);
// custom readObject method
}
}
PS: the provided workaround doesn't work since the readObject
/writeObject
methods have to be declared as private
while mine are protected
.