I would think that adding that attribute to an interface would be helpful make sure you do not create classes that use the interface and forget to make them serializable.
This could be a very fundamental question, but I wanted to ask the experts.
The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods.
When the serializer should serialize that object it knows that the object implements that interface, all it really has to do is serialize it and attach the type attribute (like it does if you serialize abstract classes or just super-classes in general).
The serialization architecture handles object types that extend MarshalByRefObject the same as types that extend Object. These types can be marked with the SerializableAttribute and implement the ISerializable interface as any other object type. Their object state will be captured and persisted onto the stream.
Serializable doesn't contain any method, it's the ObjectOutputStream and ObjectInputStream classes that can do that work, through the writeObject and readObject methods. Serializable is just a marker interface, in other words it just puts a flag, without requiring any fields or methods.
Interfaces define a contract and do not have any state of their own.
Serialization is about saving and loading state into and out of an object model.
Not much point to serializing something that holds no state.
To answer the practical question of forcing an implementation of an interface to be Serializable
- this is why the ISerializable
interface exists.
In .NET you can declare an interface that should implement other interfaces:
interface MustBeSerializable : ISerializable {}
See some more information here.
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