0

Whenever I'm doing shallow cloning then if my class consists of any user-defined reference type then there reference value will copied but not values, but if I'm writing String s="something", then even though s is an object but it is directly copied into the cloned object, why so? Does it mean pre-defined object will be copied but user-defined object reference will be copied?

yglodt
  • 13,807
  • 14
  • 91
  • 127
jyotisman
  • 83
  • 6

2 Answers2

0

If you want an object of the same state, then you can use clone(). If there's no difference between the two I would say use a constructor. Cloning requires an object to already have been made in order to make another instance, not to mention the implementation of Cloneable is already fairly messy.

Also note, the object you attempt to use clone() on must actually implement Cloneable and override the method in order to actually work.

Rogue
  • 11,105
  • 5
  • 45
  • 71
  • not exactly correct, clone() can be overridden to provide both shallow and deep copies. copy constructors can do the same thing. – TTT Apr 08 '14 at 18:21
0

It is not that "predefined" object types are deep copied and "user defined" object types are shallow copied.

Your cited example is this :

String s = "something";

Yes, a string literal is an "object" but strings are immutable objects, and more importantly they are special down to the level that they are built into the design of the language itself. REALLY what you are doing here is nothing different from saying YourClass varName = new YourClass(); Here, you create a new String object with value "something" (if the literal does not exist in the string constant pool) and store a reference to that object to your variable s of type String.

You can shallow copy a string just like you can shallow copy a user defined object:

String s = "something"; //in this example this would be the same as saying new String("something")
String imAShallowCopyOfS = s;

System.out.println(imAShallowCopyOfS == s); //true

You are still just copying the reference that s points to into imAShallowCopyOfS. I would suggest you shy away from using Strings to learn the behavior of references in java, though, as they are rather special objects that receive some special treatment by the compiler/vm.

Community
  • 1
  • 1
TTT
  • 1,952
  • 18
  • 33