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.
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.
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
If you create a new Dog:
and then:
You'd have one
Dog
and two variables that reference the sameDog
. Therefore doing:Will print that the dog has a Fedora hat, because
a
andb
reference the same dog.Instead, doing:
Now you have two dogs clones. If you put a hat on each dog:
Each dog will have its own hat.