Friday, January 25, 2013

Java Serialization Questions

How Serialization works ?

Suppose following example.

C extends B extends A.

Case 1:

if Class A implements Serializable interface. B and C need not to do it explicitly. If I create an object of class C, serialize it and deserialize, all the attributes of A, B and C will be populated.

Because while de-serialization none of the class's constructor will be called.

If any of this class have an attribute of class which don't implement Serializable Interface, while serialization exception will be thrown.

Case 2:

A and C don't implements Serializable interface but B implements.

Now in this case all the attributes of B and C will be serialized and deserialized but A's attributes will not.

Only class A's Constructor will be called during deserialization.

Other than A, if any class have an attribute of class which don't implement Serializalbe interface exception will be thrown.

Case 3:

A and B don't implements Serializable interface only C implements.

Now in this case all the attributes of A and B will not be serialized and deserialized only C's attributes will.

Only class A's and B's Constructor will be called during deserialization.

Both than A and B can have an attribute of class which don't implement Serializalbe interface.
  

Summary: If super class implements Serializable interface, child class will inherit it. 
If superclass don't implements Serializable interface and chlid class does, and if you try to serialize object of child class, only child class's attributes will be serialized.
Super class's attributes will be ignored.



Q- Example of Extenalization


class Employee implements Externalizable {
      String name;
      double salary;
      int age;
      long cardNo;

      public void writeExternal(ObjectOutput out) throws IOException {
             out.writeUTF(name);
             out.writeInt(age);
             out.writeDouble(salary);

      }

      public void readExternal(ObjectInput in) throws IOException,
                    ClassNotFoundException {
             name = in.readUTF();
             age = in.readInt();
             salary = in.readDouble();

      }
}


For more questions Refer Click here

No comments:

Post a Comment