• Post Reply Bookmark Topic Watch Topic
  • New Topic

Serialization -  RSS feed

 
Shaveta Chawla
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understood the concept pf Serialization. But i could not understand when the condition when i have a class which is final and cant be extended and i need to serialize to store the object of class. I read the book of Kathy Sierra SCJP but i am nit able to understand private implementation of writeObject and readObject methods.

class Dog implements Serializable {
transient private Collar theCollar; // we can't serialize this
private int dogSize;
public Dog(Collar collar, int size) {
theCollar = collar;
dogSize = size;
}
public Collar getCollar() { return theCollar; }
private void writeObject(ObjectOutputStream os) {
// throws IOException { // 1
try {
os.defaultWriteObject(); // 2
os.writeInt(theCollar.getCollarSize()); // 3
} catch (Exception e) { e.printStackTrace(); }
}
private void readObject(ObjectInputStream is) {
// throws IOException, ClassNotFoundException { // 4
try {
is.defaultReadObject(); // 5
theCollar = new Collar(is.readInt()); // 6
} catch (Exception e) { e.printStackTrace(); }
}
}

Please explain the code above. and why these methods should be private
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the Javadocs for Serializable, you'll see that those methods are special methods used in serialization and must be used with those exact method headers.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess the original poster understands that they have to have those signatures, but wonders why.

The simple answer to all those "why" questions is "because the JLS says so". And it's often not worth too much effort questioning it.

In this case, the private methods are called from within the JVM, which doesn't have to abide by the access modifiers. The reason for making them private is so they cannot be overridden. It would be disastrous if they were overridden, as the readObject() and writeObject() are only intended to deal with serialising exactly the class in which they appear, not any super or subclass.

I guess they could have made the requirement be that these methods were final, which would have done the trick. But no other class has any business calling them, so private seems right to me.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!