• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regarding serialization?

 
swati cha
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;
class Food {Food(){System.out.println("1");}
}
class Fruit extends Food implements Serializable{
Fruit(){System.out.println("2");}
}
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
author
Marshal
Pie
Posts: 21009
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.

Henry
 
Tony Smith
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

Thanks,

Bert

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.
 
saran bala
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic