Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

About serialization

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
author
Posts: 23909
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hint: When you run this command...



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

Henry
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic