Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 684
Robert Avatar asked Nov 24 '14 11:11

Robert


3 Answers

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.

like image 167
vz0 Avatar answered Nov 15 '22 06:11

vz0


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

like image 25
Sarthak Mittal Avatar answered Nov 15 '22 06:11

Sarthak Mittal


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.

like image 35
Kraal Avatar answered Nov 15 '22 06:11

Kraal