aspose file tools*
The moose likes Java in General and the fly likes How Inheritance Affects Serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How Inheritance Affects Serialization" Watch "How Inheritance Affects Serialization" New topic
Author

How Inheritance Affects Serialization

Dhineshkumar raj
Greenhorn

Joined: Aug 06, 2007
Posts: 28
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
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12825
    
    5
When an instance of a serializable class is deserialized, the constructor does not run, and instance variables are NOT given their initially assigned values!


Why did you expect this result? A serialized object records the state at the instant of serialization - that is the whole point of serializing.

Bill
 
 
subject: How Inheritance Affects Serialization