If I define a class as Serialiable then when I create a sub-class it asks me to define a serialVersionUID. Is this necessary or can I rely on the one in the super-class?
Asked
Active
Viewed 1,293 times
3
-
2[Why should I bother about serialVersionUID?](http://stackoverflow.com/questions/285793/why-should-i-bother-about-serialversionuid/285809#285809) – Prince John Wesley Apr 05 '11 at 08:22
-
http://stackoverflow.com/questions/285793/why-should-i-bother-about-serialversionuid – David Soroko Apr 05 '11 at 08:50
2 Answers
4
I used to declare once SerialVersionUID in separate (possibly top class), like:
public static final long GlobalSerialVersionUID=0L;
And then in each Serializable
class declare:
private static final long serialVersionUID = MyTopClass.GlobalSerialVersionUID;
this approach would guarantee that you will all time have the same SerialVersionUID and if you will be going to implement data interchange between different serialized versions - you could branch code between different serialized versions.

Barmaley
- 16,638
- 18
- 73
- 146
3
SerialVersionUID is used if you change the implementation of a class, but still want to be able to serialize/deserialise objects saved in the "old" format. So this means that you have to implement it in the subclass as well, if you want to change the subclass but not the superclass. However, if you dont need this "version control" you dont have to use SerialVersionUID at all.

AndersG
- 365
- 4
- 12
-
In that case do I override the warning and not define it at all? If so, what happens when I update my application and it tries to restore the bundle due to a previous save? – theblitz Apr 05 '11 at 09:17
-
Yes, you override it. But you will not be able to restore from a bundle if the bundle was saved with the earlier version. I'm not sure if you will get an exception or just no objects loaded. You can read up on serialization here: http://java.sun.com/developer/technicalArticles/Programming/serialization/ – AndersG Apr 05 '11 at 09:32