• 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
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Doubt on Serialization

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am reading SCJP Book, In that they given like this. when you deserialize an object, the non-serializable superclass must run its
constructor. Remember, constructors don't run on deserialized classes that implement Serializable.
As per above statement i guessed output for the below one is p only. But the correct output is pcp. Can any one explain why this is?
 
Ranch Hand
Posts: 100
Hibernate Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

In line 15, when we do a new CardPlayer(), since CardPlayer extends Player, first Player's constructor and then CardPlayer's constructors will be invoked. Making the output "pc". This is irrespective of whether serialization is in picture or not.
Now, coming to the question, the statement posted itself explains the output. CardPlayer implements Serializable but not Player class.
So, when the serialized object c1 is read back/deserialized, it realizes that its parent Player does not implement Serializable. Hence, Player's constructor will be run. So, the additional "p" at the end making the output "pcp". And, yes, as you have mentioned constructors will not run during deserialization for classes that implement serializable. Hence, constructor of CardPlayer is not invoked while deserializing c1. Hope this clarifies your question.

 
Greenhorn
Posts: 10
Python Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just to clarify a bit more,

"constructors don't run on deserialized classes that implement Serializable."

is applicable to the process of deserialization.
At line 15 in the code, a new instance is being created hence the constructor and super class constructors are being called.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic