The difference between creating an object using a new keyword and using the cloning method

What is the difference between creating an object using the new keyword and creating an object using clone() ? Is there a difference between memory allocation?

+6
source share
4 answers
Operator

new creates an instance of the new object, and clone() more like a copy constructor. clone() method creates a copy of the object with member attribute values โ€‹โ€‹also copied .

+3
source

new creates an object according to the constructor, and clone() creates a new object and initializes the fields with the contents of the original object.

I understand you are reading javadoc, so let me give you 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.

which explains the behavior of our childrenโ€™s list: links are copied, not elements that are referenced, so our copy is โ€œshallowโ€

The memory allocation may vary, of course:

  • you can initialize fields in your constructor
  • clone can initialize the field, i.e. an array
+2
source

Simple application

new creates an instance

a

clone returns the clone of the instance.

+1
source

Clone () creates a new instance of the same class and copies all the fields to the new instance and returns it (shallow copy).

and the new keyword is the Java statement that creates the object ( http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html ).

+1
source

All Articles