Nirav Prajapati
Nirav Prajapati

Reputation: 3005

Clone method behavior at memory level - java

when i am creating new object of Particular class using new keyword it occupies some memory in heap For example i have class Xyz and i am creating object of Xyz using new keyword and it occupies some memory in heap

Xyz xyz = new Xyz();

now assume that xyz have memory location 12@FFD

same object create using clone method

Xyz xyzClone =(Xyz) super.clone()

my question is if xyzClone occupies different memory in heap than xyz than why we need clone method we can achieve same behavior using new keyword ??? and if xyzClone occupies no extra memory than it may be behave like Singleton

Please clear my confusion why we need clone method ???

Upvotes: 0

Views: 2922

Answers (3)

Santhosh
Santhosh

Reputation: 8197

Creating a Object#clone means you can create an object that is similar to another object but is not the same object.

By this when you say you have cloned an object, it means that there is a different object in the heap that has the same state. But if you alter this new object, it does not alter the original object

my question is if xyzClone occupies different memory in heap than xyz than why we need clone method we can achieve same behavior using new keyword ?

the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another.

The copy constructor is used to create a copy of an object that is passed by value to a function. This is not an issue in Java, because all objects in Java programs are passed by reference.

If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.

See also :

Upvotes: 3

Deepu--Java
Deepu--Java

Reputation: 3830

Yes, you can implement the same functionality like clone by creating any new method in class. But clone gives you more control. By clone you can create shallow copy(default) as well as deep copy(if you want).

It's just in-built functionality of Object class which gives you control on object cloning.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240928

clone() creates new instance which has same state as the one from which it is cloned

Upvotes: 3

Related Questions