Q-1). What are the common problems faced while implementing Shallow Copy and Deep Copy?
A-1). Java’s clone() method performs a shallow copy by default, which may not work for objects containing references to other objects. You must implement a custom deep copy by manually cloning the referenced objects.
Q-2). Whether we can perform cloning operations on immutable objects?
A-2). Cloning cannot work with immutable objects, as their state cannot be modified. Avoid the Prototype Pattern for immutable objects; instead, use a Builder Pattern.
Q-3). What are the limitations of the Cloneable interface?
A-3). Java’s Cloneable interface does not enforce the implementation of the clone() method. It’s better to create a custom Prototype interface.
Q-4). What are the performance-related issues faced while implementing the Prototype pattern?
A-4). Deep cloning can be performance-intensive for complex objects. Optimize the cloning process or use caching to reduce overhead.
Q-5). What is Serialization based deep cloning?
A-5). Sometimes implementing the clone() method is tedious, so then, one can use Serialization for deep cloning. An example program is provided below.
public class SerializationDeepClone {
public static Object deepClone(Object object) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
}
Analysis
- Create a ByteArrayOutputStream object
- Create an ObjectOutputStream object and call writeObject() of ObjectOutputStream.
- Create a ByteArrayInputStream object.
- Create an ObjectInputStream object call the readObject() and return that because in writeObject() method you pass the object which is passed as an argument to the above deepClone().