File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes regarding serialization? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "regarding serialization?" Watch "regarding serialization?" New topic

regarding serialization?

swati cha
Ranch Hand

Joined: Jul 04, 2006
Posts: 40
class Food {Food(){System.out.println("1");}
class Fruit extends Food implements Serializable{
public class Banana extends Fruit{
int size=42;
public static void main(String a[]){
Banana b=new Banana();
b.serializeBanana(b);//assume correct serialization
b=b.deserialize(b);//assume correct
System.out.println("restore" + b.size + " ");

why the output is 121 restore 42?

can any one explain the above code,Thnaks in advance.........
Henry Wong

Joined: Sep 28, 2004
Posts: 20516

b.serializeBanana(b);//assume correct serialization
b=b.deserialize(b);//assume correct

Well, if serialization is assumed to be correct. And deserialization is assumed to be correct... then what are you asking about? The rest of the program just creates the object and prints it.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Tony Smith
Ranch Hand

Joined: Jul 07, 2007
Posts: 229
I think the 121 is because the constructor calls. When you have Banana b=new Banana(); It calls its parent constructors that's why you have 12. Then when you b=b.deserialize(b); it calls its parent constructor that is not serializable which gives you the last 1.
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
Hi Swati -

It's absolutely okay for you to post mock questions on this forum, however we have a policy that you should mention the source of the question, this helps the author!



p.s. Full disclosure is that this is one of our questions , but seriously, we'd like for you to post the sources of ALL the mock questions you'd like to discuss.

Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
saran bala

Joined: Oct 17, 2007
Posts: 8
The key point here to note here is that the constructors are not called while deserializing the object.While serializing the object,the constructors will be called.
So while serializing the b,superclass constructors are called..output is 1 2.then while deserilasing the object,since the food is not serialised,its constructor is called once again and the output is 1 and finally restore and 42.
I agree. Here's the link:
subject: regarding serialization?
It's not a secret anymore!