Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Serialization

 
Shivey Upadhyay
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Shivey Upadhyay
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
I was
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic