If something inherits from a Serializable class, is the child class still Serializable?
You must explicitly mark each derived class as [Serializable] . If, however, you mean the ISerializable interface, then yes: interface implementations are inherited, but you need to be careful - for example by using a virtual method so that derived classes can contribute their data to the serialization.
In Java, an object is said to be serializable if its class or parent classes implement either the Serializable interface or the Externalizable interface. Deserialization is converting the serialized object back into a copy of the object.
Case 2(a): What happens when a class is serializable, but its superclass is not? Serialization: At the time of serialization, if any instance variable inherits from the non-serializable superclass, then JVM ignores the original value of that instance variable and saves the default value to the file.
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java. io.
It depends what you mean be serializable. If you mean the CLI marker (i.e. the [Serializable]
attribute), then this is not inherited (proof below). You must explicitly mark each derived class as [Serializable]
. If, however, you mean the ISerializable
interface, then yes: interface implementations are inherited, but you need to be careful - for example by using a virtual
method so that derived classes can contribute their data to the serialization.
using System;
class Program
{
static void Main()
{
Console.WriteLine(typeof(Foo).IsSerializable); // shows True
Console.WriteLine(typeof(Bar).IsSerializable); // shows False
}
}
[Serializable]
class Foo {}
class Bar : Foo {}
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