Am preparing for
SCJP 1.5 exam.
I have a doubt Serialization chapter,
In that you can find How Inheritance Affects Serialization
Just see the following code and i will ask my doubt at the end.
import java.io.*;
class SuperNotSerial {
public static void main(
String [] args) {
Dog d = new Dog(35, "Fido");
System.out.println("before: " + d.name + " "+ d.weight);
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(d);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
d = (Dog) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("after: " + d.name + " "+ d.weight);
}
}
class Dog extends Animal implements Serializable {
String name;
Dog(int w, String n) {
weight = w; // inherited
name = n; // not inherited
}
}
class Animal { // not serializable !
int weight = 42;
}
The above program which produces the output:
before: Fido 35
after: Fido 42
We know that when we create an object immediately, the constructor is invoked, which immediately invokes the superclass constructor.
Look the second try catch in the above program ,
Am creating new dog object that comes from the deserialization, not creating using new. like, d = (Dog) ois.readObject();
But these things do NOT happen when an object is deserialized. When an instance of a serializable class is deserialized, the constructor does not run, and instance variables are NOT given their initially assigned values!
Can any one give me the clear idea??
and what is happening in the above program