2

Any changes on the cloned object will it reflect the original object?.Please anyone explain how clone() method works internally.

Balasubramani
  • 645
  • 3
  • 9
  • 16

1 Answers1

6

So cloning is about creating the copy of original object. Its dictionary meaning is : “make an identical copy of“.

By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:

1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.

2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

If you want a clone which is independent of original and making changes in clone should not affect original. then you can use the Deep cloning

Here's the complete guide: http://howtodoinjava.com/2012/11/08/a-guide-to-object-cloning-in-java/

Dyrandz Famador
  • 4,499
  • 5
  • 25
  • 40