Thursday 25 August 2016

Is Serializable interface has any methods?


Serializable interface don't have any methods and fields in it, it is just a marker interface. When your class implements Serializable interface, it notifies Java compiler that use Java in built serialization mechanism while serializing the instances (objects) of this class.

Employee.java
import java.io.Serializable;

public class Employee implements Serializable{
    int id;
    String firstName, lastName;
    
    Employee(int id, String firstName, String lastName){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

}


Test.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {
  public static void main(String args[]) throws IOException, ClassNotFoundException {
    /* Serialize object */
    FileOutputStream fos = new FileOutputStream("ser.out");
    ObjectOutputStream out = new ObjectOutputStream(fos);
    Employee emp = new Employee(1, "Krishna", "Arjun");
    out.writeObject(emp);

    /* Deserialize object */
    FileInputStream fis = new FileInputStream("ser.out");
    ObjectInputStream in = new ObjectInputStream(fis);
    Employee emp1 = (Employee) in.readObject();

    System.out.println(emp1.id + " " + emp1.firstName + " " + emp1.lastName);
  }
}


Output
1 Krishna Arjun


You may like

No comments:

Post a Comment