Javatpoint Logo
Javatpoint Logo

Java Clone Examples

Object cloning indicates the production of a precise duplicate of an article. It makes another occurrence of the class of the ongoing article and introduces every one of its fields with the very items in the comparing fields of this item.

Utilizing Assignment Operator to make a duplicate of the reference variable,

In Java, there is no operator to make a duplicate of an object. In contrast to C++, in Java, in the event that we utilize the task administrator, it will make a duplicate of the reference variable and not the article. This can be made sense of by taking a model. The accompanying example shows something similar.

Example

Output:

Java Clone Examples

Creating a Duplicate Utilizing the Clone() Method

The class whose Object's duplicate is to be made a priority a public clone strategy in it or in one of its parent classes.

Each class that executes clone() ought to call super.clone() to get the cloned object reference.

The class should likewise execute Java.lang.Cloneable interface whose article clone we need to make. If not, it will toss CloneNotSupportedException when the cloning strategy is approached that class' Object.

Syntax:

protected Object clone() throws CloneNotSupportedException

Types of Object Cloning

  1. Shallow Cloning: At whatever point the default cloning method is executed, shallow Cloning occurs. Shallow Cloning basically duplicates every one of the fields of the article into the new example. Shallow Cloning is upheld by clone().
  2. Deep Cloning: Presently, every time we don't carry out the default cloning method, we are practising deep Cloning. Deep Cloning functions according to our necessities. Presently, the significant distinction here is that deep Cloning duplicates every one of the fields alongside the item's qualities, while Shallow Cloning just duplicates the fields.
  3. Lazy Cloning: There's a third kind of Cloning that is upheld in Java, which is a blend of the previously mentioned two sorts of Cloning; it is known as Lazy Cloning. Also, there is no particular rule on when to utilize which cloning type; it has arrived to choose according to our necessities.

At the point when we use the default execution of the clone method, we get a shallow copy of an object implies it makes a new occurrence and duplicates all the field of the Object to that new example and returns it as an object type. We really want to expressly project it back to our unique Object. This is a shallow duplicate of the item.

clone() method for the object class supports a shallow duplicate of the article. On the off chance that the item contains crude along with non-crude or reference type variable in shallow duplicate, the cloned Object likewise alludes to a similar item to which the first item alludes as just the article references get replicated and not the alluded objects themselves.

That is the reason the name is a shallow copy or shallow Cloning in Java. If, by some stroke of good luck, crude sort fields or Unchanging items are there, then there is no distinction between shallow and deep duplicates in Java.

Clone() Method Example-Shallow Copy

In the beneath code model, the clone() method creates a totally new item with an alternate hashCode value, and that implies it's in a different memory area. Be that as it may, because the Test object c is inside Test2, the crude sorts have accomplished profound duplicate, yet this Test object c is as yet divided among t1 and t2. To beat that, we explicitly make a profound duplicate for object variable c.

Example program to create a shallow copy:

Output:

Java Clone Examples

In the above model, t1.clone returns the shallow duplicate of the object t1. To get a profound duplicate of the item, certain changes must be made in the clone method in the wake of getting the duplicate.

Clone() Method Example-Deep Copy

If we want to make a deep copy of object X and spot it in another object Y, then another duplicate of any referred-to object fields is made, and these references are put in Object Y. This implies any progressions made in referred-to protest fields in object X or Y will be reflected exclusively in that Object and not in the other. In the beneath model, we make a deep copy of the item.

A deep copy duplicates all fields and makes duplicates of powerfully designated memory highlighted by the fields. A profound duplicate happens when an article is replicated alongside the items to which it alludes.

Example program to create a deep copy:

Output:

Java Clone Examples

In the above model, we can see that another object for the HelloWorld class has been appointed to duplicate an item that will be gotten back to the clone technique. Because of this, t2 will get a profound duplicate of the object t1. So any progressions made in the 'c' object fields by t2 won't be reflected in t1.

Difference between Shallow Copy and Deep Copy

  1. Shallow duplicate is the method for replicating an object and is trailed as a matter of course in Cloning. In this method, the fields of an old object X are duplicated to the new Object Y. While replicating the item type field, the reference is duplicated to Y i.e. object Y will highlight a similar area as brought up by X. On the off chance that the field esteem is a crude sort, it duplicates the worth of the crude kind.
  2. Consequently, any progressions made in referred to objects in object X or Y will be reflected in different objects.
  3. Shallow duplicates are available at low cost and are easy to make

Situations where Deep and Shallow Copies are Comparative

1. In Strings:

We should realize what will happen while making a duplicate of the string. We, as a whole, realize strings are considered as the objects of the class String present in the Java.lang bundle. Thus, like different articles, when we do duplicate, the reference is copied.

Example:

Output:

Java Clone Examples

Explanation:

The result of the program shows that the hash code shown by the reference factors s1 and s2 is something very similar. It implies that a similar memory area is referred to by the reference factors obj1 and obj2. However, the inquiry is, might we at any point say that we have done the shallow copy in the above program, as the reference is something similar? The response is no. The accompanying model offers us enough proof to approve the given response.

Example:

Output:

Java Clone Examples

Explanation:

The result of the program lets us know that the hash code shown by the reference variable s1 isn't equivalent to the hash code shown by the reference variable s2. Additionally, the progressions done utilizing the reference variable s2 aren't shown by the reference variable s1. It is on the grounds that strings in Java are consistently unchanging. Thusly, when s2 changes the substance of s1, it winds up making a completely new string. Subsequently, the past string stays immaculate, and the reference variable obj2 focuses on another memory place where the new string object is sitting.

We have seen that an adjustment of a string brings about the production of another string object verifiably. Consequently, replicating a string can not be named as the deep nor as the shallow copy. Truth be told, there is no distinction between profound and shallow copy when we are managing strings in Java.

2. In Primitive Data Types:

We should realize what will happen while making a duplicate of the primitive data type. Not at all like strings, the crude information types are not objects. Be that as it may, like strings, there is no understanding of profound or shallow copy in the crude information types. Notice the below model.

Output:

Java Clone Examples

Explanation:

At the point when the value of s2 is refreshed, it isn't influencing the value of s1. It is on the grounds that y, as of now, has its own memory designation. It isn't alluding to the memory area of s1. Accordingly, the assertion s2 = s1; just duplicates the worth of s1 in s2. Accordingly, any update in y never influences x. A comparative idea can be applied to the next crude information types too. Here, memory distribution for s2, too, for s4 is going on verifiably.

In Java, there is no standard expressing when to utilize shallow copy and when to utilize deep copy. It really depends on the software engineers or designers to conclude what they need to utilize. In this way, it is prescribed to comprehend the prerequisite and then, at that point, choose prudently among deep and shallow copies.

Advantages of Clone() Method

  1. On the off chance that we utilize the assignment operator to appoint an article that refers to another reference variable, then it will highlight a similar location area of the old item, and no new duplicate of the article will be made. Because of this, any progressions in the reference variable will be reflected in the first article.
  2. On the off chance that we utilize a copy constructor, we need to duplicate every one of the information unequivocally. For example, we need to expressly reassign every one of the fields of the class in the constructor. Yet, in the clone technique, this work of making another duplicate is finished by the actual strategy. So to abstain from additional handling, we use object cloning.
  3. You don't have to compose extensive and tedious codes. Simply utilize an abstract class with a 4-or 5-line long clone() method.
  4. It is the least demanding and most effective way for replicating objects, particularly on the off chance that we are applying it to an all-around created or an old undertaking. Simply characterize a parent class, execute Cloneable in it, give the meaning of the clone() strategy and the errand will be finished.
  5. Clone() is the quickest method for duplicating an array.

Disadvantages of Clone() Method

  1. To utilize the Object.clone() method, we need to change a ton of language syntax to our code, such as carrying out a Cloneable point of interaction, characterizing the clone() method and dealing with CloneNotSupportedException, lastly, calling Object.clone() and so forth.
  2. We need to execute a cloneable connection point while it has no methods in it. We simply need to utilize it to let the JVM know that we can perform clone() on our article.
  3. clone() is secured, so we need to give our own clone() and in a roundabout way call Object.clone() from it.
  4. clone() summons no constructor, so we have zero commands over object development.
  5. All to compose a clone technique in a youngster class, then its superclasses ought to characterize the clone() strategy in them or acquire it from another parent class. In any case, the super.clone() chain will fall flat.
  6. clone() upholds just shallow replicating, yet we should supersede it, assuming we really want profound Cloning.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA