What does Serializable mean? [duplicate]
Asked Answered
E

13

170

What exactly does it mean for a class to be Serializable in Java? Or in general, for that matter...

Enneahedron answered 7/8, 2010 at 9:36 Comment(4)
@skaffman Here's what it says for the class Serializable: Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.Enneahedron
A great explanation if you already know what serialized and deserialized mean. (Not a compliment.) Such definitions help you understand the issue better technically once, and only once, you already have some knowledge on it.Precipitin
@RitwikBose So , java.io.Serializable is a tag interfaceComplimentary
If you're new to java. This is a practical application of polymorphism. If a class implements an interface then that class can be passed on to anywhere its parent can be accepted as arguments. In this case the child class could be passed on to functions like Results.writeOutput(Serializable s)Tailgate
W
158

Serialization is persisting an object from memory to a sequence of bits, for instance for saving onto the disk. Deserialization is the opposite - reading data from the disk to hydrate/create an object.

In the context of your question, it is an interface that if implemented in a class, this class can automatically be serialized and deserialized by different serializers.

Willmert answered 7/8, 2010 at 9:40 Comment(3)
Also note that all fields not explicitly marked otherwise will be serialized too. This means that you can save a complex datastructure easily just by serializing the root object.Anthesis
So when we're talking about "Objects", do we mean the object instantiated by a class, or just any "Software Objects" like assemblies, files, etc.? And if its the latter, is it just a standardized way of sending data between programs and environments?Stifling
@Sunburst275 - in this case, this is the in memory representation of a class in memory - i.e. an instance of a class (there isn't a real point to talking about serialization of assemblies, as they are usually on disk as files which can simply be sent around as is).Willmert
W
54

Though most of the users have already given the answer, but I would like to add an example for those who need it in order to explain the idea:

Let's say you have a class person like the following:

public class Person implements java.io.Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public String firstName;
    public String lastName;
    public int age;
    public String address;

    public void play() {
        System.out.println(String.format(
                "If I win, send me the trophy to this address: %s", address));
    }
    @Override
    public String toString() {
        return String.format(".....Person......\nFirst Name = %s\nLast Name = %s", firstName, lastName);
    }
}

and then you create an object like this:

Person william = new Person();
        william.firstName = "William";
        william.lastName = "Kinaan";
        william.age = 26;
        william.address = "Lisbon, Portugal";

You can serialise that object to many streams. I will do that to two streams:

Serialization to standard output:

public static void serializeToStandardOutput(Person person)
            throws IOException {
        OutputStream outStream = System.out;
        ObjectOutputStream stdObjectOut = new ObjectOutputStream(outStream);
        stdObjectOut.writeObject(person);
        stdObjectOut.close();
        outStream.close();
    }

Serialization to a file:

public static void serializeToFile(Person person) throws IOException {
        OutputStream outStream = new FileOutputStream("person.ser");
        ObjectOutputStream fileObjectOut = new ObjectOutputStream(outStream);
        fileObjectOut.writeObject(person);
        fileObjectOut.close();
        outStream.close();
    }

Then:

Deserialize from file:

public static void deserializeFromFile() throws IOException,
            ClassNotFoundException {
        InputStream inStream = new FileInputStream("person.ser");
        ObjectInputStream fileObjectIn = new ObjectInputStream(inStream);
        Person person = (Person) fileObjectIn.readObject();
        System.out.println(person);
        fileObjectIn.close();
        inStream.close();
    }
Weddle answered 24/8, 2015 at 12:56 Comment(1)
So basically you can only print an object to a file in the form of its object properties if you add "implements Serializable" to the beginning of your Java class? ok...Aeneous
B
43

It means that instances of the class can be turned into a byte-stream (for example, to be saved to a file) and then converted back into classes again. This reloading could happen in a different instance of the program, or even on a different machine. Serialisation (in any language) involves all sorts of issues, though, especially when you've got references to other objects inside the serialisable one.

Biconcave answered 7/8, 2010 at 9:39 Comment(0)
I
21

Here is a detailed explanation of the Serialization: (my own blog)

Serialization:

Serialization is the process of serializing the state of an object is represented and stored in the form of a sequence of bytes. This can be stored in a file. The process to read the state of the object from the file and restoring it is called deserialization.

What is the need of Serialization?

In modern day architecture, there is always a need to store object state and then retrieve it. For example in Hibernate, to store a object we should make the class Serializable. What it does, is that once the object state is saved in the form of bytes it can be transferred to another system which can then read from the state and retrieve the class. The object state can come from a database or a different jvm or from a separate component. With the help of Serialization we can retrieve the Object state.

Code Example and explanation:

First let's have a look at the Item Class:

public class Item implements Serializable{

    /**
    *  This is the Serializable class
    */
    private static final long serialVersionUID = 475918891428093041L;
    private Long itemId;
    private String itemName;
    private transient Double itemCostPrice;
    public Item(Long itemId, String itemName, Double itemCostPrice) {
        super();
        this.itemId = itemId;
        this.itemName = itemName;
        this.itemCostPrice = itemCostPrice;
      }

      public Long getItemId() {
          return itemId;
      }

     @Override
      public String toString() {
          return "Item [itemId=" + itemId + ", itemName=" + itemName + ", itemCostPrice=" + itemCostPrice + "]";
       }


       public void setItemId(Long itemId) {
           this.itemId = itemId;
       }

       public String getItemName() {
           return itemName;
       }
       public void setItemName(String itemName) {
            this.itemName = itemName;
        }

       public Double getItemCostPrice() {
            return itemCostPrice;
        }

        public void setItemCostPrice(Double itemCostPrice) {
             this.itemCostPrice = itemCostPrice;
        }
}

In the above code it can be seen that Item class implements Serializable.

This is the interface that enables a class to be serializable.

Now we can see a variable called serialVersionUID is initialized to Long variable. This number is calculated by the compiler based on the state of the class and the class attributes. This is the number that will help the jvm identify the state of an object when it reads the state of the object from file.

For that we can have a look at the official Oracle Documentation:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long: ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; 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. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.

If you have noticed there is another keyword we have used which is transient.

If a field is not serializable, it must be marked transient. Here we marked the itemCostPrice as transient and don't want it to be written in a file

Now let's have a look on how to write the state of an object in the file and then read it from there.

public class SerializationExample {

    public static void main(String[] args){
        serialize();
       deserialize();
    } 

    public static void serialize(){

         Item item = new Item(1L,"Pen", 12.55);
         System.out.println("Before Serialization" + item);

         FileOutputStream fileOut;
         try {
             fileOut = new FileOutputStream("/tmp/item.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut);
             out.writeObject(item);
             out.close();
             fileOut.close();
             System.out.println("Serialized data is saved in /tmp/item.ser");
           } catch (FileNotFoundException e) {

                  e.printStackTrace();
           } catch (IOException e) {

                  e.printStackTrace();
           }
      }

    public static void deserialize(){
        Item item;

        try {
                FileInputStream fileIn = new FileInputStream("/tmp/item.ser");
                ObjectInputStream in = new ObjectInputStream(fileIn);
                item = (Item) in.readObject();
                System.out.println("Serialized data is read from /tmp/item.ser");
                System.out.println("After Deserialization" + item);
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        } catch (IOException e) {
               e.printStackTrace();
        } catch (ClassNotFoundException e) {
               e.printStackTrace();
        }
     }
}

In the above we can see an example of serialization and deserialization of an object.

For that we used two classes. For serializing the object we have used ObjectOutputStream. We have used the method writeObject to write the object in the file.

For Deserializing we have used ObjectInputStream which reads from the object from the file. It uses readObject to read the object data from the file.

The output of the above code would be like:

Before SerializationItem [itemId=1, itemName=Pen, itemCostPrice=12.55]
Serialized data is saved in /tmp/item.ser
After DeserializationItem [itemId=1, itemName=Pen, itemCostPrice=null]

Notice that itemCostPrice from deserialized object is null as it was not written.

Incorporating answered 26/4, 2017 at 0:11 Comment(1)
This is a nice explanation! Thank you! But to be honest, this entry looks much cleaner than the one on your blog. Anyways, this helped a lot!Stifling
F
13

Serialization involves saving the current state of an object to a stream, and restoring an equivalent object from that stream. The stream functions as a container for the object

Freddafreddi answered 7/8, 2010 at 9:47 Comment(1)
This definition seems more precise. Thank you.Bremser
W
6

Serializable is called in like an interface but its more like a flag to the the Serialization subsystem, at runtime. It says this object can be saved. All the Objects instance variables with the exception of none serializable objects and ones mark volatile will be saved.

Imagine your application can change colour as an option, without keeping that setting external you would need to change the colour every time you ran it.

Woodring answered 7/8, 2010 at 9:40 Comment(2)
It is not a 'flag to the compiler'. It is a flag to the Serialization subsystem, at runtime.Kathykathye
If I hadn't of wrote it I wouldn't of been corrected and would be worse off. All the other answers have left off transient too. You didn't even write an answer, you're just trolling other peoples.Woodring
L
4

Serialization is a technique to storing or writing the objects and data in to files. By using ObjectOutputStream and FileOutputStream classes. These classes having their specific methods to persist the objects. like writeObject();

for clear explantaion with figures . See Here for more info

Lowland answered 13/1, 2012 at 9:10 Comment(0)
I
4

To present from another perspective. Serialization is a kind of interface called 'marker interface'. A marker interface is an interface that contains no method declarations, but merely designates (or “marks”) a class that implements the interface as having some property. If you understand polymorphism this will make very much sense. In the case of the Serializable marker interface, the ObjectOutputStream.write(Object) method will fail if its argument does not implement the interface. This is a potential mistake in java, it could have been ObjectOutputStream.write(Serializable)

Highly Recommended : Reading Item 37 from Effective Java by Joshua Bloch to learn more.

Inkblot answered 2/6, 2014 at 9:41 Comment(0)
K
3

Serialization: Writing State of Object to File/Network or anywhere. ( Mean Java Object Supported form to File Supported Form or Network Supported Form )

Deserialization: Reading State of Object from File/Network or anywhere. ( Mean File/Network Supported form to Java Object Supported Form )

Kinny answered 25/10, 2015 at 18:48 Comment(0)
C
1

Just to add to the other answers and with regards to generality. Serialization is sometimes known as archiving, for example in Objective-C.

Constellation answered 7/8, 2010 at 11:53 Comment(0)
A
0

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.Externalizable. Deserialization is the process of converting the serialized form of an object back into a copy of the object

Click here to see more.

Ampulla answered 4/2, 2021 at 17:0 Comment(0)
A
0

Serialization is used to export application data into a file.

deserialization to extract the data from the application .

Example :

namespace DemoApplication
{
  [Serializable]
  class Tutorial
  {
  public int ID;
  public String Name;
   static void Main(string[] args)
   {
    Tutorial obj = new Tutorial();
    obj.ID = 1;
    obj.Name = ".Net";

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Create,FileAccess.Write);

    formatter.Serialize(stream, obj);
    stream.Close();

    stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Open,FileAccess.Read);
    Tutorial objnew = (Tutorial)formatter.Deserialize(stream);

    Console.WriteLine(objnew.ID);
    Console.WriteLine(objnew.Name);

    Console.ReadKey();
  }
 }
}
Ablaut answered 7/2, 2023 at 13:49 Comment(0)
R
0

Serializable is an interface called marker-interface just to tell Java I want to make serialization and de-serialization using this Java calss.

Serialization: Write to the file or any other storage like a database.

De-serialization: read from a file or any other storage like a database.

Ruffo answered 27/11, 2023 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.