Wednesday, 8 February 2017

SERIALIZATION WITH RESPECT TO INHERITANCE IN JAVA

If the parent class implements Serializable then automatically every child class implements Serializable which means Serializable nature is inherited from parent to child.

Example –
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class Abc implements java.io.Serializable{
          int i=10;
}
class Xyz extends Abc{
          private long accno;
          int i=20;
}
public class InheritanceSerializable {
          public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
                   Xyz obj1 = new Xyz();
                   ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("xyz.txt"));
                   oos.writeObject(obj1);
                   ObjectInputStream ois = new ObjectInputStream(new FileInputStream("xyz.txt"));
                   Xyz obj2 = (Xyz)ois.readObject();
                   System.out.println(obj2.i);
          }
}

Output –
20

No comments:

Post a Comment