If I want to Serialize a java object, I just have to implement marker interface Serializable
, which does not have any methods.
class Employee implements Serializable{
private int id;
private String name;
/*
private void writeObject(ObjectOutputStream out) throws IOException{
System.out.println("in write object");
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
System.out.println("in read object");
}
*/
}
My queries (EDIT):
By implementing marker interface
Serializable
in my code, Java is serializing the my object. Which class is responsible for Serialization of java objects implementingSerializable
interface ?What is the entry point for this process? Who calls ObjectOutputStream?
Even without implementing
Externalizable
interface, private methods of my class :readObject
andwriteObject
have been invoked. These have been commented in above code to enable default Java Serializaiton. Why is it allowed in first place without explicitly implementingExternalizable
interface?
EDIT: To make my question clear, why did Java allow private readObject & writeObject
methods instead of forcing up to use Externalizable
implementation to customize Serialization process.
From Java docs:
The writeExternal and readExternal methods of the Externalizable interface are implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate with the supertype to save its state. These methods supersede customized implementations of writeObject and readObject methods.
Are both mechanism not achieving the same result?