Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to clone() an object?

Tags:

clone

What is object cloning in vb6 or java? In what situation do we use a clone? What does cloning objects mean? Can any one tell me with example please.

like image 413
pbrp Avatar asked Nov 17 '09 15:11

pbrp


People also ask

What is the use of clone () method?

The clone() method is used to create a copy of an object of a class which implements Cloneable interface.

Why do we clone object?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing time to be performed that is why we use object cloning.

What is object cloning explain?

The object cloning is a way to create an exact copy of an object. For this purpose, the clone() method of an object class is used to clone an object. The Cloneable interface must be implemented by a class whose object clone to create.


1 Answers

Cloning is actually copying the object data into a new object.

This example doesn't clone the data:

Foo p = new Foo();
Foo o = p;

If Foo has a member a and you change p.a then o.a also changes because both p and o point to the same object.

However,

Foo p = new Foo();
Foo o = p.Clone();

In this case if you change p.a then o.a remains the same because they actually point to separate objects.

There are actually two different ways you can clone: shallow clone or deep clone.

A shallow clone just makes a new object and copies the members into the new object. This means that if one of the members is actually a pointer to another object then that object will be shared between the old object and new object.

A deep clone actually goes through and clones all the members into the new object. That way the objects are complete copies of all the data.

like image 169
Aaron Avatar answered Sep 28 '22 01:09

Aaron