Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is serialVersionUID inherited by subclasses, if I have default serialVersionUID in superclass [closed]

Is serialVersionUID inherited by subclasses, if I have default serialVersionUID in superclass? Similar to when the superclass is serializable then subclasses are also serializable.

I had a superclass initially with no default serialVersionUID so I was getting:

local class incompatible: stream classdesc serialVersionUID = -3473908186986930430, 
local class serialVersionUID = -7527159820765531130

So I added this to the superclass:

private static final long serialVersionUID = 1L;

My question is: does serialization consider serialVersionUID from superclass when serializing subclasses or not. Do I need to specify serialVersionUID in every subclass explicitly?

like image 344
user3603110 Avatar asked May 05 '14 05:05

user3603110


People also ask

What happens if two classes have same serialVersionUID?

The serialVersionUID is specific to a class, not an object, since they are static. I don't think it matters if two different classes have the same serialVersionUID, since it is used in deserializing objects of the same class.

What is serialVersionUID what would happen if you don't define this?

The SerialVersionUID can be used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible w.r.t serialization. If the deserialization object is different than serialization, then it can throw an InvalidClassException.

What will happen if I will not declare serialVersionUID in a class which implements Serializable?

If serialVersionUID is not provided in a Serializable class, the JVM will generate one automatically. However, it is good practice to provide the serialVersionUID value and update it after changes to the class so that we can have control over the serialization/deserialization process.

Do subclasses need to implement Serializable?

Yes. Subclass need not be marked serializable explicitly.


1 Answers

Is serialVersionUID inherited by subclasses, if I have default serialVersionUID in superclass?

No it is not inherited, because it is private, and in any case Serialization won't consider it as belonging to the subclass and not use it.

Similar to when the superclass is serializable then subclasses are also serializable.

It isn't similar. Serializable is an interface and it is subject only to the rules of the language. serialVersionUID is a special field with its own rules enforced by ObjectInputStream.

like image 107
user207421 Avatar answered Sep 23 '22 09:09

user207421