Serialization in Java – 1

Serialization in java is a topic in it-self. More often then not, we are caught unaware of a few serialization principles. Here, we try to cover two important aspects in the context of inheritance.
a. Super-class is Serializable. How to ensure that a Child-class shouldn’t be Serializable?
Solution:Add default private methods of readObject() and writeObject() in the Child-class and throw a NotSerializableException.

class SuperClass implements Serializable{
     private String state;

     public SuperClass(String state){
         this.state=state;
     }

     public String getState(){
         return state;
     }
     public String setState(String state){
         this.state=state;
     }
}

class ChildClass extends SuperClass{

    private void writeObject(ObjectOutputStream out) throws IOException{
          throw new NotSerializableException("Dont serialize me!");
    }
    private void readObject(ObjectInputStream in) throws IOException{
          throw new NotSerializableException("Dont serialize me!");
    }

}

b. Super-class is not Serializable. How to ensure that a Child-class should be Serializable?
Solution: Provide a no-arg constructor in the Super-class and make it accessible to the child-class.

class SuperClass  {
     private String state;

     public SuperClass(){
     }

     public SuperClass(String state){
         this.state=state;
     }

     public String getState(){
         return state;
     }
     public String setState(String state){
         this.state=state;
     }

}

class ChildClass extemds SuperClass implements java.io.Serializable{

}

Courtesy:

Todd Greanier’s article
John Zukowski’s article
StackOverFlow

For a quick read on Serialization, refer this article.

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