Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Serializable interface contain any methods? [duplicate]

I know what is serialization and why it is used, but my question:

  1. Why is serialization a marker interface?
  2. What is the potential benefit of not having writeObject, readObject in Serializable interface because when we do serialization we finally override these 2 methods?
  3. How does readResolve ensure that the object created during deserialization is not the new object. I know the below and it is returning the same object during deserialization but who will call this readResolve method internally?

    private Object readResolve() throws java.io.ObjectStreamException { 
        return INSTANCE;
    }
    
like image 366
Lathy Avatar asked Jul 14 '15 06:07

Lathy


Video Answer


2 Answers

  1. Because there needs to be some explicit way of declaring a class to be serializable. The framework can't just assume all classes to be serializable, as there are many kinds of objects that will stop working if their fields are written to disk and are later reloaded from there (e.g. FileInputStream, which relies on an open operating system file handle which might no longer exist when the object is deserialized). The modern way of having such a declaration would be an annotation, but those didn't exist in Java at the time serialization was added.
  2. You won't necessarily need to override them - if the default behavior of the serializer is good enough; you don't need to do anything but implement Serializable.
  3. The serialization framework calls it when an object has been completely deserialized. At this time, the object is allowed to inspect its own contents, and if it decides that it should instead be represented by another instance, it can return that instance instead (if not, it returns this). Whatever comes out of this method is returned to the code that requested the deserialization. If a preexisting object was returned, the new object created by the deserializer will not be seen by anyone and will eventually be garbage collected.
like image 183
Aasmund Eldhuset Avatar answered Sep 20 '22 15:09

Aasmund Eldhuset


Marker Interfaces are used to tell JVM to perform specific tasks. they don't have any method. Serializable is also a marker interface.

Serialization is the process of flattening the objects. when you implement serializable interface in a class, it tells JVM to serialize its object i.e. it has to be converted into stream.

like image 45
Vivek Mishra Avatar answered Sep 18 '22 15:09

Vivek Mishra