Shallow Copy Java
In Java, creating a clone or copy of an object is the most important task. In this section, we will discuss what is a shallow copy in Java and how to create a shallow copy of a Java object. Before moving to the shallow copy, first, we will understand what is a copy in Java and the difference between a reference copy and an object copy.
As the name indicates, a reference copy creates a copy of a reference variable pointing to an object. For example, if we have a Byke object, with a myByke variable pointing to it and we make a reference copy, we will now have two myByke variables, but still one object.
An object copy creates a copy of the object itself. So, if we again copied our byke object, we would create a copy of the object itself, as well as a second reference variable referencing that copied object.
A shallow copy of an object is a new object whose instance variables are identical to the old object. For example, a shallow copy of a Set has the same members as the old Set and shares objects with the old Set through pointers. Shallow copies are sometimes said to use reference semantics.
In other words, we can say that in shallow copy only references are copied. Therefore, both original and object point to the same reference. Creating a new reference that points to the same memory location. Note that when we try to alter data in the copied object, the changes are also reflected in the original one.
When we create a copy of an object using a shallow copy mechanism, all fields of the original objects are copied. On the other hand, if it contains objects as fields, only the references to those objects are copied but not complete objects. A point to remember is that only primitive data types are copied while the object references are not copied.
Note: The clone() method of the Object class creates a shallow copy, by default.
Consider the following code snippet.
Shallow Copy Java Program
Original (orginal values): Person-A - Civic Clone (before change): Person-A - Civic Clone (after change): Person-B - Accord Original (after clone is modified): Person-A - Accord
Shallow Copy Vs. Deep Copy