Suggested Pages

Wednesday, May 30, 2012

Serialization

Serialization is the process of converting a data structure or object state into a format that can be stored.
In Java an object to be serialized must implement the java.io.Serializable interface.

Serialization and Inheritance


Suppose you have the following classes:
A.java

public class A implements Serializable {
  
  protected int variableA=3;
  
  public static void main(String [] args){
        B b=new B();
        b.variableA=4;
        b.variableB=7;
        serialize(b);
        b=(B) deserialize(b);
        System.out.println(b.variableA);  
        System.out.println(b.variableB);  

  }

  // this method serializes object o
  private void serialize(Object o){
     ...
  }
  // this method deserializes object o
  private Object deserialize(Object o){
     ...
  }
}

class B extends A {
      
   private int variableB=2;
}

The output of the program is the following

    4 
    7 
Because the class B extends A, B is automatically a serializable class. During ​​the deserialization no constructor of A and B is invoked, so the instance fields of A ​​and B are restored correctly.
Instead suppose your classes are:
A.java

 public class A {

  protected int variableA=3;

  public static void main (String [] args){
        B b=new B();
        b.variableA=4;
        b.variableB=7
        serialize(b);
        b=(B) deserialize(b);
        System.out.println(b.variableA);  
        System.out.println(b.variableB);        
  }

  // this method serializes object o
  private void serialize(Object o){
     ...
  }
  // this method deserializes object o
  private Object deserialize(Object o){
     ...
  }
}

  class B extends A implements Serializable{
     
    private int variableB=2;
 } 

The output of the program is the following

    3 
    7 


The value of the field variableA is not restored; its value is reinitialized to 3 value. During deserialization, the fields of the first non-serializable superclass (A class) will be initialized using the public or protected no-arg constructor of the class.

Serialization and Transient keyword

Suppose you have these classes:
A.java

 public class A implements Serializable{
    private B b=new B();
    private int variableA=3;

  public static void main (String [] args){
      A a =new A();
      serialize(a);       
 }

  class B {
     private int variableB=2;
 } 

}
In this case we'll have a Runtime Exception: throws NotSerializableException . This exception occurs because B is not marked as transient.
If an object doesn't implement Serializable interface, it must be marked with transient keyword. The consequence is that when you persist an instance of A, you'll find a null value in place of B state.

No comments :

Post a Comment

Suggested Pages