问题
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 ?
回答1:
If the parent is tagged as Serializable then every child should be serializable by design. Otherwise the bad design choice is not how you forbid serialization by throwing exceptions but the fact that Parent shouldn't have been Serializable.
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 transient but this is not always possible, if the field contains critical information).
回答2:
The probable reason this might have happened is that the parent class may have originally been designed not as a parent class, but rather just normal serializable class. So later on, someone created a child class that wasn't serializable - that doesn't mean that the parent class has a "design flaw".
If you may have a particular child class that isn't Serializable, the only downside is a possible runtime exception if serialization is attempted. If you know that your non-serializable child class won't ever be serialized by your application, then there's no real problem.
回答3:
Since Serializable is only a tagging interface, I don't see too much sense in the above construct. In Java there is no way to shadow this interface, which means that you are at the mercy of the code that is using your Child class. It may handle Serialization exceptions or may not.
One example when it handles such classes is when you've got some classes in a Java web container session, which gets persisted/restored to/from disk. In this case, Tomcat and other containers usually only give a warning but do not exit.
来源:https://stackoverflow.com/questions/11125738/under-what-circumstance-would-you-want-your-child-class-to-avoid-serializable-if