Table of contents
1.
Introduction
2.
Declaration
3.
Example
3.1.
Java
4.
Frequently Asked Questions
4.1.
What happens if a non-serializable class is inherited by a serializable class?
4.2.
Can static fields be serialized?
4.3.
What is the purpose of the serialVersionUID field?
5.
Conclusion
Last Updated: Jul 29, 2024
Easy

Serializable Interface in Java

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, the Serializable interface is a simple tool for converting objects into a format that can be stored or transmitted & then recreated later. This process, known as serialization, allows you to save the state of an object and restore it when needed, making it useful for tasks like network communication & data persistence. 

Serializable Interface in Java

In this article, we'll discuss the basics of the Serializable interface, like its declaration & usage, and a practical code example to help you understand how it works.

Declaration

To make a class serializable in Java, you must implement the Serializable interface. Here's how you declare a class as serializable:

import java.io.Serializable;
public class MyClass implements Serializable {
    // Class members and methods go here
}


By adding "implements Serializable" to your class declaration, you're telling Java that instances of this class can be serialized. The Serializable interface doesn't have any methods you need to implement; it's just a marker interface indicating the class's ability to be serialized.

It's important to note that all the fields in a serializable class must also be serializable. If a field is not serializable, you can mark it as transient to exclude it from the serialization process:

private transient int nonSerializableField;


When an object is deserialized, transient fields will be initialized with their default values (e.g., null for object references, 0 for numeric types, and false for booleans).

Example

Let's take a look at an example that shows how to use the Serializable interface to serialize and deserialize an object:

  • Java

Java

mport java.io.*;

public class Person implements Serializable {

   private static final long serialVersionUID = 1L;

   private String name;

   private int age;

   public Person(String name, int age) {

       this.name = name;

       this.age = age;

   }

  @Override

   public String toString() {

       return "Person{" +

               "name='" + name + '\'' +

               ", age=" + age +

               '}';

   }

   public static void main(String[] args) {

       Person person = new Person("Rahul", 25);

       // Serialization

       try {

           FileOutputStream fileOut = new FileOutputStream("/tmp/person.ser");

           ObjectOutputStream out = new ObjectOutputStream(fileOut);

           out.writeObject(person);

           out.close();

           fileOut.close();

           System.out.println("Serialized data is saved in /tmp/person.ser");

       } catch (IOException e) {

           System.err.println("Serialization failed: " + e.getMessage());

           e.printStackTrace();

       }

       // Deserialization

       Person deserializedPerson = null;

       try {

           FileInputStream fileIn = new FileInputStream("/tmp/person.ser");

           ObjectInputStream in = new ObjectInputStream(fileIn);

           deserializedPerson = (Person) in.readObject();

           in.close();

           fileIn.close();

       } catch (IOException e) {

           System.err.println("Deserialization failed: " + e.getMessage());

           e.printStackTrace();

       } catch (ClassNotFoundException e) {

           System.err.println("Person class not found: " + e.getMessage());

           e.printStackTrace();

       }




       if (deserializedPerson != null) {

           System.out.println("Deserialized Person object:");

           System.out.println(deserializedPerson);

       }

   }

}
You can also try this code with Online Java Compiler
Run Code

In this example, we define a Person class that implements Serializable. The class has two fields: name (String) & age (int), both of which are serializable.

Inside the main method, we create an instance of the Person class & serialize it to a file named "person.ser" using FileOutputStream & ObjectOutputStream. We then deserialize the object from the file using FileInputStream & ObjectInputStream, casting the result back to a Person object.

Finally, we print out the deserialized Person object to verify that the serialization and deserialization process worked correctly.


Output

Serialized data is saved in person.ser
Deserialized Person object:
Person{name='Rahul', age=25}


This code example shows the complete usage of the Serializable interface in Java. The Person class implements Serializable, allowing its instances to be serialized and deserialized.

The main method performs the following steps:

  1. It creates an instance of the Person class with the name "Rahul" and age 25.
     
  2. It serializes the Person object and saves it to a file named "person.ser" using FileOutputStream and ObjectOutputStream.
     
  3. It deserializes the object from the "person.ser" file using FileInputStream and ObjectInputStream.
     
  4. Finally, it prints the deserialized Person object to the console to verify that the serialization and deserialization process worked correctly.

Frequently Asked Questions

What happens if a non-serializable class is inherited by a serializable class?

If a serializable class inherits from a non-serializable class, the non-serializable class must have a no-arg constructor to allow deserialization of the serializable subclass.

Can static fields be serialized?

No, static fields belong to the class itself rather than instances of the class, so they are not serialized.

What is the purpose of the serialVersionUID field?

The serialVersionUID is used to verify that the serialized and deserialized objects are compatible. If not specified, the JVM will generate one automatically, but it's recommended to declare it explicitly to avoid issues with different class versions.

Conclusion

In this article, we've learned about the Serializable interface in Java, which enables the serialization and deserialization of objects. 

We explained how to declare a class as serializable, use transient fields for non-serializable data, and saw an example of serializing and deserializing a Person object. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass