5

I am really confused about what is the difference between .clone() method or simply putting the = sign between objects while trying to clone it.

Thank You.

Robert
  • 103
  • 2
  • 8

5 Answers5

19

If you create a new Dog:

Dog a = new Dog("Mike");

and then:

Dog b = a;

You'd have one Dog and two variables that reference the same Dog. Therefore doing:

a.putHatOnHead("Fedora");

if (b.hasHatOnHead()) {
    System.out.println("Has a hat: " + b.getHatName());
}

Will print that the dog has a Fedora hat, because a and b reference the same dog.

Instead, doing:

Dog b = a.clone();

Now you have two dogs clones. If you put a hat on each dog:

a.putHatOnHead("Rayden");
b.putHatOnHead("Fedora");

Each dog will have its own hat.

vz0
  • 32,345
  • 7
  • 44
  • 77
3

Let me try to explain you:

Object obj = new Object();  //creates a new object on the heap and links the reference obj to that object

Case 1:

Object obj2 = obj;  //there is only one object on the heap but now two references are pointing to it.

Case 2:

Object obj2 = obj.clone(); //creates a new object on the heap, with same variables and values contained in obj and links the reference obj2 to it.

for more info on clone method, you can refer the java api documentation

Sarthak Mittal
  • 5,794
  • 2
  • 24
  • 44
  • Thank you for your effort, now I comfortably can say that I understood the whole concept :) – Robert Nov 24 '14 at 13:21
1

The = sign is the assignment operator in java. Having a = b means "I assign to the variable a the value of variable b. If b is an object, then a = b makes a point to the object that b is pointing to. It does not copy the object, nor clone it.

If you want to clone an object you either have to do it by hand (ugly), or have to make the class that has to be clonable to implement Clonable then call clone().

The advantage on clone() over the "ugly" way is that with clone() it's the developer of the class to be cloned that defines how cloning has to be done in order to ensure that the copy is a legit and working copy.

Kraal
  • 2,779
  • 1
  • 19
  • 36
0

With = you are just giving the same object a different name. With .clone you are creating a new object that is a copy of the original one.

-3

= creates a new reference to the same object. clone() creates a new physical object with the same attributes as the earlier one

Blasanka
  • 21,001
  • 12
  • 102
  • 104
Anmol Parikh
  • 23
  • 1
  • 2
  • 4
  • 3
    When the question have been answered years ago, please don't answer if you don't have anything to add. Everything you say is already included in previous answers. – klutt May 26 '17 at 23:17
  • 2
    _@AnmolParikh_ Just to notify you. Your answer is currently discussed at Meta Stack Overflow: https://meta.stackoverflow.com/questions/349781/how-do-i-vote-late-answers-when-there-are-much-better-answers – πάντα ῥεῖ May 26 '17 at 23:29