• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables are never saved during Serialization, yet my code seems to do the opposite

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I just finished Chapter 6 of Sierra/Bates, and now I am on Chapter 7 that begins its discussion with Hashing. I modified the following code, based on Chapter 7:



My output is:

45 50
0 50



I would think that the output is:

45 50
0 5


because in deserialization, the constructor is called, and y gets it's static value of 5. Please explain.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The constructor is not called for your 'Serializable' class. If the JVM must reload
the class, however, the statics will revert to their initialized values. Otherwise, if
you serialize and then immediately deserialize, static values are untouched.

Jim ... ...
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When recreating an instance from a serialized object, the constructor with no parameters is used. Because you did not specify this constructor, the compiler creates one for you.

EDIT: I tried my own test (creating a constructor with no parameters) and found I was wrong. Looks like it's back to reading the book for me :-)

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where can I find an example program that demonstrates static variables reverting to their original values after class is de-serialized. Or better yet, how can I modify the code I posted to perform this action. Please guide.
 
Unmesh Chowdhury
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sandra, Jim Hoglund is correct. You can decompose your code into three parts as follows:

1st Part:

2nd Part:
(As separate compilation unit)

3rd Part:
(As individual CU)


I think, you can experiment now.
 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the code to experiment with, now I understand better!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic