-3

In general to make a copy of object, we assign it to a new object like :

Object a = new Object();
Object b = a;

While doing this, what all things we need to take care of? I guess Object a and b are dependent on each other as they will be pointing to same location so changing the value in one will change in other also. Please correct if its wrong.

Also, is this way is different from cloning or we can consider it as a cloning only.

If its cloning, will this do the deep cloning or shallow?

AalekhG
  • 361
  • 3
  • 8
  • Wrong already. That assignment does not create a copy of an object. It creates another reference to the *same* object. – user207421 Jul 24 '16 at 07:25

4 Answers4

1

First statement created a pointer that point to newly created object in memory. second statement set the variable point to the same location. that means both pointers point to the same object in memory. And yes you can change the state of the object from any pointer. Pointers are just like address in the memory.

Cloning is different thing. basically you create the whole copy of the object in another location and point to it using a variable. so

Object a = new Object(); Object b = a.clone();

now b points to a new object in memory. initially both objects will be identical but totally disconnected. changing object a will have no effect on object b.

Shahzad

Shahzad Aslam
  • 172
  • 1
  • 12
0

It is not cloning at all. It is just giving another name to the same object as a and b are pointing to the exact same object.

Bon
  • 3,073
  • 5
  • 21
  • 40
0

Both the references points to the same object.

The out of box implementation of Object.clone() method does shallow copy. If an object has one association inside it lets say a employee object having address object, then when we clone the employee object only it's primitive properties are copied when we use Object.clone(). Both the original and cloned copy will point to the same address object.

One way to achieve deep cloning is user serialization. First serialize the object and then deserialize it. Java will creating all together new objects while deserializing.

Rahul Vedpathak
  • 1,346
  • 3
  • 16
  • 30
0

Its not cloning.. Object a = new Object(); Object b = a;. It means object 'a' and 'b' are pointing to same memory location. When we clone an object. The state of other object is stored in new object but not memory location.

Imtiaz Ali
  • 302
  • 1
  • 3
  • 8