what is object deep copy and shallow copy and why it is
required?
Answer Posted / sanjay
Java provides a mechanism for creating copies of objects
called cloning.
There are two ways to make a copy of an object called
1. shallow copy
2. deep copy
Shallow copy is a bit-wise copy of an object. A new
object is created that has an exact copy of the values in
the original object. If any of the fields of the object are
references to other objects, just the references are copied.
Thus, if the object you are copying contains references to
yet other objects, a shallow copy refers to the same subobjects.
Deep copy is a complete duplicate copy of an object.
If an object has references to other objects, complete new
copies of those objects are also made. A deep copy generates
a copy not only of the primitive values of the original
object, but copies of all subobjects as well, all the way to
the bottom. If you need a true, complete copy of the
original object, then you will need to implement a full deep
copy for the object.
Java supports shallow and deep copy with the
Cloneable interface to create copies of objects. To make a
clone of a Java object, you declare that an object
implements Cloneable, and then provide an override of the
clone method of the standard Java Object base class.
Implementing Cloneable tells the java compiler that your
object is Cloneable. The cloning is actually done by the
clone method.
| Is This Answer Correct ? | 11 Yes | 0 No |
Post New Answer View All Answers
What is Classloader in Java?
What is module with example?
What is the class in java?
What is mutable object and immutable object?
How to make object serializable in java?
What is struts in java?
Is string passed by reference in java?
State the merge-sort principle and its time complexity.
What is the epoch date?
Add a value x to array from index l to r where 0 <= l <= r <= n-1
Explain about arraylist?
Can we have two main methods in a java class?
What are the restrictions imposed on method overriding?
Give example to differentiate between call by value and call by reference.
What is the original name of java?