I read that in general abstract classes should not be made Serializable in Java. Subclasses must be serializable (with custom methods for reading, writing, if necessary, for example, when abstract classes have fields).
What is the reason for this? Why is this considered a bad design?
Update1: I have an abstract class with some fields and three subclasses. At the moment I am using the following approach.
I made all subclasses serializable with custom read, write methods. In an abstract class, I have the following methods.
void writeFields(ObjectOutputStream out)throws IOException { .... } void readFields(ObjectInputStream in) throws IOException, ClassNotFoundException{ ... }
In custom reading methods, writing to subclasses, I call these methods to (de) serialize fields in an abstract class. Is this approach right? Or is there another better approach?
Update 2: I took Tom's advice and made my abstract class Serializable. (I want all subclasses to be Serializable, and I have data in an abstract class). It's aloof, but to complete the story, I use reflection to change the final field, as Jeremy Manson advised.
java oop serialization abstract-class
athena
source share