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?
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.
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.
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.
Yes. Subclass need not be marked serializable explicitly.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With