What is the difference between creating an object using the new
keyword and creating an object using clone()
? Is there any difference between memory allocation?
new
creates an object according to the constructor, while clone()
creates a new object and initializes the fields with the contents of the original object.
I take it, you read the javadoc, so let me take you through an example:
public class MyBaby implements Cloneable {
int age = 0;
String name = "Dolly";
List<String> list = new ArrayList<String>();
public static void main(String[] args) {
MyBaby originalBaby = new MyBaby();
originalBaby.setAge(1);
try {
// We clone the baby.
MyBaby clonedBaby = (MyBaby) originalBaby.clone();
// both babies now have: age 1, name "Molly" and an empty arraylist
originalBaby.setAge(2);
// originalBaby has age 2, the clone has age 1
originalBaby.setName("Molly");
// same goes for the String, both are individual fields
originalBaby.getList().add("addedString");
// both babies get the string added to the list,
// because both point to the same list.
System.out.println(clonedBaby.toString());
}
catch (CloneNotSupportedException e) {}
}
}
The javadoc says:
this method performs a "shallow copy" of this object, not a "deep copy" operation.
which explains the behaviour of our babies' list: References are copied, not the elements that are referenced, thus our copy is "shallow"
The memory allocation can differ of course:
new
operator instantiates the new object while clone()
is more like a copy constructor. clone()
method creates a copy of the object with values of member attributes also copied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With