Serialization is the process of converting an object's state into a byte stream so it can be saved to a file, stored in a database, or transmitted over a network. Deserialization is the reverse: reconstructing the object from the byte stream.
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
transient String password; // 'transient' fields are NOT serialized
}
// Serialize
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("emp.dat"));
out.writeObject(employee);
out.close();
// Deserialize
ObjectInputStream in = new ObjectInputStream(new FileInputStream("emp.dat"));
Employee emp = (Employee) in.readObject();
in.close();
Cloning creates an exact copy of an existing object. There are two types:
Copies the object's field values directly. If a field is a reference to another object, only the reference is copied (both the original and the clone point to the SAME inner object).
Recursively copies all objects referenced by the original. The clone is completely independent.
// Shallow clone in Java
class Student implements Cloneable {
String name;
Address address; // Reference type
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
// Deep clone
protected Object clone() throws CloneNotSupportedException {
Student cloned = (Student) super.clone();
cloned.address = new Address(this.address); // Deep copy the Address
return cloned;
}
An alternative to cloning. A constructor that takes an object of the same class and creates a new object with the same values. More explicit and less error-prone than clone().
class Student {
String name;
Address address;
// Copy Constructor
Student(Student other) {
this.name = other.name;
this.address = new Address(other.address); // Deep copy
}
}
Many modern style guides prefer Copy Constructors or static factory methods over Java's Cloneable interface, which is considered a broken API by Joshua Bloch in "Effective Java."