• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt about serialization in java  RSS feed

 
rizwana mujawar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The author says "When an instance of a serialized class is deserialized,the constructor does not run and instance variables are not given their initially assigned values"...
Can someone help me understand this lines by giving some example...
Thanks..
 
Sunni srivastav
Greenhorn
Posts: 24
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In context of java "instance" means object.

When we create an object,we create it by using new keyword over its constructor.

Consider the below class:


Now if we are creating object of this class using the default constructor


and fetch the value for its members
then we get the default values

fruitName=Mango
fruitColor=Yellow

Now we go ahead and change these values using setters


After this the members become

fruitName=Apple
fruitColor=Red


After doing all these you serialize the object and then deserialize it.Now please go ahead and fetch the values you will get

fruitName=Apple
fruitColor=Red

implying that the object was persisted/stored and then the same object is reconstructed with the stored object info in the file which you specify during serialization.So the constructor is not called while doing all these.Hence its instance variables were not assigned the initial values.

Suggestion:Whenever you are reading anything try and implement it.Then the concept will become more clear.
 
Gaurangkumar Khalasi
Ranch Hand
Posts: 187
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rizwana mujawar wrote:The author says "When an instance of a serialized class is deserialized,the constructor does not run and instance variables are not given their initially assigned values"...
Can someone help me understand this lines by giving some example...
Thanks..


Serialization is the process of storing any object contents in to a File. So, when you say serialized class i.e. it able to be stored/retrieved its object contents from a file by implementing Serializable interface.
When you want to get back that data you have to deserialized that object from a file and definitely you can take it in any instance of the same class(currently do not refer to any object. i.e. its value will be null ). So, if during that deserialization, constructor will run you will get default values rather than your stored values...Therefore, during deserialization constructor doesn't run.

Examples:
http://www.java-samples.com/showtutorial.php?tutorialid=398
http://www.roseindia.net/java/example/java/io/serializingobject.shtml



 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!