Thursday, November 14, 2013

Cloning and Serialization

Cloneable Interface

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. 
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. Clone() for details on overriding this method.

Cloning produces shallow copy of the object by default. 

Serializable Interface

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized.  All subtypes of a serializable class are themselves serializable.  The serialization interface has no methods or fields
and serves only to identify the semantics of being serializable.

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields.  The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to
initialize the class's state.  It is an error to declare a class Serializable if this is not the case.  The error will be detected at runtime. Serialization produces deep copy of the object always.

If class does not implement serializable interface and trying to serialize the object throws java.io.NotSerializableException.
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: SearilizableObject
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1332)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at SerializationTest.main(SerializationTest.java:38)
Caused by: java.io.NotSerializableException: SearilizableObject
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at SerializationTest.main(SerializationTest.java:27)

No comments:

Post a Comment