Thursday, September 4, 2025
HomeLanguagesJavaSerializable Interface in Java

Serializable Interface in Java

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. Classes implement it if they want their instances to be Serialized or Deserialized. Serialization is a mechanism of converting the state of an object into a byte stream. Serialization is done using ObjectOutputStream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. Deserialization is done using ObjectInputStream. Thus it can be used to make an eligible for saving its state into a file. 

Declaration

public interface Serializable

Example: The below example shows a class that implements Serializable Interface.

Java




// Java Program to demonstrate a class
// implementing Serializable interface
  
import java.io.Serializable;
  
public static class Student implements Serializable {
    public String name = null;
    public String dept = null;
    public int id = 0;
}


Here, you can see that Student class implements Serializable, but does not have any methods to implement from Serializable.

Example: Below example code explains Serializing and Deserializing an object.

Java




// Java program to illustrate Serializable interface
import java.io.*;
  
// By implementing Serializable interface
// we make sure that state of instances of class A
// can be saved in a file.
class A implements Serializable {
    int i;
    String s;
  
    // A class constructor
    public A(int i, String s)
    {
        this.i = i;
        this.s = s;
    }
}
  
public class Test {
    public static void main(String[] args)
        throws IOException, ClassNotFoundException
    {
        A a = new A(20, "GeeksForGeeks");
  
        // Serializing 'a'
        FileOutputStream fos
            = new FileOutputStream("xyz.txt");
        ObjectOutputStream oos
            = new ObjectOutputStream(fos);
        oos.writeObject(a);
  
        // De-serializing 'a'
        FileInputStream fis
            = new FileInputStream("xyz.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        A b = (A)ois.readObject(); // down-casting object
  
        System.out.println(b.i + " " + b.s);
  
        // closing streams
        oos.close();
        ois.close();
    }
}


Output:

20 GeeksForGeeks

Must Read: Serialization and Deserialization in Java

RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS