What is the difference between cloning an object using .clone () and = sign?

I am really confused by what constitutes the difference between a method .clone()or simply by placing a sign =between objects when trying to clone it.

Thank.

+4
source share
5 answers

If you create a new dog:

Dog a = new Dog("Mike");

and then:

Dog b = a;

You will have one Dogand two variables that reference the same Dog. Therefore:

a.putHatOnHead("Fedora");

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

Displays that the dog has the Fedora hat, because it aand brefer to the same dog.

Instead, run:

Dog b = a.clone();

You now have two dog clones. If you put a hat on each dog:

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

.

+13

:

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

1:

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

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.

, java api

+3

= - java. a = b " a b. b - , a = b a , b. .

, (), , Clonable, clone().

clone() "" , clone() , , , , , .

+1

= . .clone , .

0

= . clone() ,

-3

All Articles