Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About serialization

 
C Law
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure I understand how the state of an object is preserved.

For one thing:

Animal a = new Animal();
try{
FileOutputStream fo = new FileOutputStream("test.ser");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(a);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}

What is test.ser? Is it an actual file? How can I found it?

Secondly, it seems that I can modify instance variable after
the object containing it has been serialized:

public class Animal{
String name = "Mutsang";

public static void main(String[] argv){
Animal a = new Animal();
try{
FileOutputStream fo = new FileOutputStream("test.ser");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(a);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}

a.name = "Tiger";

try{
FileInputStream fi = new FileInputStream("test.ser");
ObjectInputStream oo = new ObjectInputStream(fi);
oo.readObject();
System.out.println(a.name);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}
//output is Tiger.

If the state is really saved in "test.ser", how come that when
the object is restored, its "name" field is changed?

Thanks in advance!
 
Henry Wong
author
Marshal
Pie
Posts: 21114
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hint: When you run this command...



What do you think happens to the object that is returned?

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic