If parent is not serialized and child class are serialized .Then parent class variable will not persist or we can save the state of parent class will not persist in file .
Example
import java.io.FileInputStream;
import
java.io.FileOutputStream;import
java.io.ObjectInputStream;import
java.io.ObjectOutputStream;import
java.io.Serializable;class NonSerial {
public int a=0;
}
class Serial2 extends NonSerial implements Serializable{
public int a2=2;
}
class Serial1 extends Serial2 {
public int a1=1;
}
public
class MyClass extends Serial1 implements Serializable{/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String [] args) {
MyClass c = new MyClass();
try {
c.a1=1223;
c.a2=1223;
c.a=1223;
FileOutputStream fs = new FileOutputStream("d://test1.txt");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("d://test1.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
MyClass cc = (MyClass) ois.readObject();
System.out.println("c0:"+cc.a+"\nc1:"+cc.a1+"\nc2:"+cc.a2);
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
If we write and read the persist object (serialized object )then we will find the output is as following .It shows that value of a ia not persist and it again we we read its initialized value which is 0 is display as output .
Output
c0:0 c1:1223 c2:1223 |
Read More →