7

For one of my projects, I need to define a new exception which extends ProviderMismatchException.

From the javadoc link, you can see that this exception:

  • extends IllegalArgumentException, which
  • extends RuntimeException, which
  • extends Exception, which
  • extends Throwable.

All of them define their own static final serialVersionUID except for Throwable which adds the private modifier.

Now, if you implement an interface Foo, then all inherited classse also implement that interface, and this stands for Serializable as well; however, why do subclasses in the JDK redefine it for each subclass? What is the danger of not defining it again for inherited classes?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
fge
  • 119,121
  • 33
  • 254
  • 329

1 Answers1

4

The serialVersioUID is a static long value, thus it won't be inherited through the class hierarchy.

You need this to indicate if a prior serialized instance of a class has the same version as the current implementation or not.

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

For Details see here:

What is a serialVersionUID and why should I use it?

Community
  • 1
  • 1
Marcinek
  • 2,144
  • 1
  • 19
  • 25