aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Serialization" Watch "Serialization" New topic
Author

Serialization

Shivey Upadhyay
Greenhorn

Joined: Oct 05, 2007
Posts: 29
Hi,
I was goin through Serialization! from KS & BB book. I came to know if superclass does not implement Serializable, when object(of subclass-implementing serializable) is read back, the states(inherited instance variables) that it inherited from its superclass are set to default.
I also saw an example and implemented it! however it is not givin me the desired RESULT.
import java.io.*;
class Animal{
int weight = 42;
}
class Dog extends Animal implements Serializable{
String name;
Dog(String n, int w){
name = n;
weight = w;
}
}
public class SuperNotSerail {
public static void main(String[] args){
Dog d = new Dog("test", 22);
System.out.println("before: "+d.name+" "+d.weight);
try{
File f = new File("c:/shivey/scjprob", "SuperNotSerial.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d);
oos.close();
//Now Taking Written Object Back
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
ois.readObject();
ois.close();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("after: "+d.name+" "+d.weight);
}
}

Both times the output is
before: test 22
after: test 22
I am not sure why? Have i done any mistake?
Pls, i have been always a lil in this subject(Serializable).
Thanks,
Shivey


Thanks,
Shivey
SCJP, SCWCD, and Aspiring SCDJWS
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
It looks like you didn't actually read the serialized object back into d. Instead of just

you need to do something like


Right now, your code is not modifying d at all, which is why you see no change after deserialization.


SCJP 5.0
Shivey Upadhyay
Greenhorn

Joined: Oct 05, 2007
Posts: 29
Thanks!
I was
 
 
subject: Serialization