Difficult Java interview questions – Serialization

This article is a follow-up to my article here

a. Are static variables serializable?

Ans: Static and transient variables of a class are not serializable. 

b. Can a class implement both Serializable and Externalizable?

Ans: Yes, the class can implement both Serializable and Externalizable.

c. What happens to the non-serializable objects in a class while serializing which implements Serializable?

Ans: The class fails to serialize with exception  java.io.NotSerializableException.

d. What happens to the non-serializable objects in a class while serializing which implements Serializable, Externalizable?

Ans: The class can be serialized and de-serialized successfully.

e. How do we deal with serialVersionUID when a class implements Serializable?

Ans:  If we don’t provide a serialVersionUID,  java compiler generates a serialVersionUID based on the properties defined in the class. Hence, if we have modified the class with a new property after a class has been serialized, then it will fail while de-serializing as a new serialVersionUID is generated by java compiler again. So, to get around this issue, we can fix the serialVersionUID of a class to be 1L. 

f. If we have a Serializable class “MyClass” which extends “MySuperClass”. What happens to the properties of “MySuperClass”, when we serialize/de-serialize “MyClass”?

Ans: If the properties inside the “MySuperClass” are serializable like primitives,serializable classes then all these will be available in the sub-class during/after serialization. However, if there are non-serializable properties, then there should be a default constructor in “MySuperClass” provided.

g. How do we serialize the non-serializable properties of a super-class[non-serializable] in a serializable sub-class?

Ans: We will have to over-ride the default private writeObject() and readObject() methods of sub-class and provide values for the non-serializable properties. Otherwise, ensure that the non-serializable properties are set with some default/specific values while creating the sub-class it-self. Refer below for sample code:

import java.io.*;

public class TestSerialization {
    public static void main(String args[]) {
        // Object serialization
        try {
            MyClass object1 = new MyClass("Hello");
            System.out.println("object1: " + object1);
            FileOutputStream fos = new FileOutputStream("serial");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(object1);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            System.out.println("Exception during serialization: " + e);
            System.exit(0);
        }
        // Object deserialization
        try {
            MyClass object2;
            FileInputStream fis = new FileInputStream("serial");
            ObjectInputStream ois = new ObjectInputStream(fis);
            object2 = (MyClass) ois.readObject();
            ois.close();
            System.out.println("object2: " + object2);
        } catch (Exception e) {
            System.out.println("Exception during deserialization: " + e);
            System.exit(0);
        }
    }
}

class FailSerilization{
    String y="fail serilization";
}

class MySuperClass{
    String x="not super";
    FailSerilization fs;

//    MySuperClass(FailSerilization fs){
//        this.fs=fs;
//    }
    MySuperClass(){
        fs=new FailSerilization();
    }

}

class MyClass extends MySuperClass implements Serializable {
    String s;

    public MyClass(String s) {
        //super(new FailSerilization());
        this.s = s;

    }

    public String toString() {
        return "s=" + s + ";x= "+x+"; fs= "+fs.y;
    }
}

More here:

class MyClass extends MyClass2 implements Serializable{

  public MyClass(int quantity) {
    setNonSerializableProperty(new NonSerializableClass(quantity));
  }

  private void writeObject(java.io.ObjectOutputStream out)
  throws IOException{
    // note, here we don't need out.defaultWriteObject(); because
    // MyClass has no other state to serialize
    out.writeInt(super.getNonSerializableProperty().getQuantity());
  }

  private void readObject(java.io.ObjectInputStream in)
  throws IOException {
    // note, here we don't need in.defaultReadObject();
    // because MyClass has no other state to deserialize
    super.setNonSerializableProperty(new NonSerializableClass(in.readInt()));
  }
}

/* this class must have no-arg constructor accessible to MyClass */
class MyClass2 {

  /* this property must be gettable/settable by MyClass.  It cannot be final, therefore. */
  private NonSerializableClass nonSerializableProperty;

  public void setNonSerializableProperty(NonSerializableClass nonSerializableProperty) {
    this.nonSerializableProperty = nonSerializableProperty;
  }

  public NonSerializableClass getNonSerializableProperty() {
    return nonSerializableProperty;
  }
}

class NonSerializableClass{

  private final int quantity;

  public NonSerializableClass(int quantity){
    this.quantity = quantity;
  }

  public int getQuantity() {
    return quantity;
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s