Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are interfaces not [Serializable]?

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.

like image 645
Zac Harlan Avatar asked Apr 14 '10 16:04

Zac Harlan


People also ask

Are interfaces Serializable?

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.

Can we serialize interface C#?

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).

What is the use of Serializable interface in C#?

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.

Why does Serializable have no methods?

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.


1 Answers

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.

like image 141
Oded Avatar answered Sep 20 '22 18:09

Oded