26
class A implements Serializable{
    private static final long serialVersionUID = 5L;
    ...
}

and

class B implements Serializable{
    private static final long serialVersionUID = 6L;
    ...
}

then it is necessary to give unique serialVersionUID to both classes.

So can I assign serialVersionUID = 5L for both classes?

I read following links

Why generate long serialVersionUID instead of a simple 1L?

What is a serialVersionUID and why should I use it?

Community
  • 1
  • 1
Darshan Patel
  • 3,176
  • 6
  • 26
  • 49

4 Answers4

25

Yes, you can. Serial versions of different classes are independent and do not interfere each other.

PS
Eclipse even proposes you to set serialVersionID by default value that is 1L.

Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32
11

serialVersionUID is needed to remember versions of the class. It should be same while serializing and deserializing. It is a good programming practice to provide this value rather than JVM assigning one(generally it is hash). It is not necessary for two classes to have unique values.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
4

serialVersionUID can be anything.

But the best practice is to start with the lowest number (for example 0L) and update it whenever you make a change in class which affects serialization, for example, adding/updating/removing a field, in which case you should increase the version number from 0L to 1L and so on.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • @Reman Sahasi, "adding/updating/removing a field, in which case you should increase the version number from 0L to 1L and so on." - Here if we updated 0L to 1L then how we should get previously serialized objects? Since previously serialized objects are stored with 0L. – Raj Nov 22 '21 at 05:55
  • @Raj why do _you_ want to get previously serialized objects? This property is basically used during serialization process to verify that a loaded class and the serialized object are compatible. – Raman Sahasi Dec 22 '21 at 05:59
  • @Reman Sahasi, Lets assume, If you saved one object in a file using serialization with 0L serialVersionUId then later you added few columns into class (That is class modified/fields removed) and you updated serialVersionUID from 0L to 1L then you saved latest data with 1L into the file. So in this file if you have both versions Serialized objects, then how can we get previously stored data with 0L with same Serialization class? – Raj Dec 23 '21 at 10:43
1

SerialVersionUUID is an identifier used by a compiler to serialize/deserialize an object. This id is a private member to the class.

Creating new uuid for every serializable is good to have control over the serialization/deserialization process but it need NOT be unique among different classes.

Nitin
  • 21
  • 2