Search code examples
javaservletsweb-applicationsserializationserializable

Basics of Serialization in java not understood


I am not able to understand the basics of Serialization in Java 1.6.

Below is the Dog Class containing an instance variable of Collar Class:

Dog.java

public class Dog implements Serializable {

private Collar collar;

public Collar getCollar() {
    return collar;
}

public void setCollar(Collar collar) {
    this.collar = collar;
}

}

The Collar class does not implements Serializable interface as shown below:

Collar.java

public class Collar {

private int size;

public int getSize() {
    return size;
}

public void setSize(int size) {
    this.size = size;
}

}

Now when I try to serialize the Dog then why it does not throw an NotSerializableException ? According to the contract the entire object graph should implement Serializable but my Collar class does not fulfill that.

Below is the main method for this demo:

public static void main(String[] args) {
    try {
        FileOutputStream fs = new FileOutputStream("E:\\test.ser");
        ObjectOutputStream os = new ObjectOutputStream(fs);
        Dog dog = new Dog();
        // No exception thrown here, WHY?
        // test.ser file is getting created properly.
        os.writeObject(dog);

        FileInputStream fis = new FileInputStream("E:\\test.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Dog dog1 = (Dog)ois.readObject();
        // Here I am getting a null Collar object
        Collar c1 = dog1.getCollar();

Kindly explain this, I am totally confused while trying to implement all the theoretical stuffs :(


Solution

  • It appears that you had a misunderstanding of the concept of object graph. In this graph, the nodes are instances (not classes) and the edges are formed from values of reference-typed instance variables.

    Applied to your example,

    Dog dog = new Dog();
    

    creates an object graph consisting of a single node, the Dog instance. The collar variable is null so its value doesn't form an edge no another node. But, if you add a line such as

    dog.setCollar(new Collar());
    

    now your object graph contains two nodes, connected by the edge formed by the value in the collar instance variable.

    Now, all this applied to serialization means that your posted example is serializing the one-node object graph, whose all nodes are serializable, but if you added a collar, that graph would contain a non-serializalbe node and you would get the exception you expect.