Q1) What are different types of cloning in Java?
Ans) Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in Java. Object class has a method clone() which does shallow cloning.
Q2) What is Shallow copy?
Ans) In shallow copy the object is copied without its contained objects.
Shallow clone only copies the top level structure of the object not the lower levels.
It is an exact bit copy of all the attributes.
Figure 1: Original java object obj
The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not copied.
Figure 2: Shallow copy object obj1
It can be seen that no new objects are created for obj1 and it is referring to the same old contained objects. If either of the containedObj contain any other object no new reference is created
Q3) What is deep copy and how it can be acheived?
Ans) In deep copy the object is copied along with the objects it refers to. Deep clone copies all the levels of the object from top to the bottom recursively.
Figure 3 : Original Object obj
When a deep copy of the object is done new references are created.
Figure 4: obj2 is deep copy of obj1
One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes. This may be the best solution if you need a complex mixture of deep and shallow copies for different fields, but has a few significant drawbacks:
Other common solution to the deep copy problem is to use Java Object Serialization (JOS). The idea is simple: Write the object to an array using JOSâ€™s ObjectOutputStreamand then use ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects. JOS takes care of all of the details: superclass fields, following object graphs, and handling repeated references to the same object within the graph.
There are ways to speed it up (e.g., by pre-computing serial version ids and defining custom readObject() and writeObject() methods), but this will usually be the primary bottleneck. The byte array stream implementations included in the java.io package are designed to be general enough to perform reasonable well for data of different sizes and to be safe to use in a multi-threaded environment. These characteristics, however, slow down ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream .
Q4) What is difference between deep and shallow cloning?
Ans) The differences are as follows:
Q5) What are the characteristics of a shallow clone?
Ans) If we do a = clone(b)
1) Then b.equals(a)
2) No method of a can modify the value of b.
Q6) What are the disadvantages of deep cloning?
Ans) Disadvantages of using Serialization to achieve deep cloning –