What is the difference between cloning the object with .clone() method and = sign?

4.3k views Asked by At

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.

5

There are 5 answers

1
vz0 On BEST ANSWER

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.

0
Marko Živanović On

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.

0
Kraal On

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.

1
Sarthak Mittal On

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

2
Anmol Parikh On

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