class Parent implements Serializable{
........
}
class Child extends Parent{
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
private void readObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
}
The above code shows how child avoids Serializable if the parent is already implemented Serializable. It seems to be a bad design and confusing at some points, so I am wondering in what circumstance would you consider to do that ?
If the parent is tagged as
Serializablethen every child should be serializable by design. Otherwise the bad design choice is not how you forbid serialization by throwing exceptions but the fact thatParentshouldn’t have beenSerializable.Since there is no way to remove an interface implemented in a an ancestor class you have no choices: raising an exception is always better then serialize something which is not meant to be serialized, this would let you think everything went fine until something will go wrong with the serialized data. There is always a reason to forbid serialization: just adding a field in the child class which is not serializable is enough (unless you can use it as
transientbut this is not always possible, if the field contains critical information).