Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between creating an object using new keyword and using clone method

Tags:

java

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?

like image 766
Siddhanta Kumar Pattnaik Avatar asked Nov 03 '12 04:11

Siddhanta Kumar Pattnaik


2 Answers

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:

  1. you can initialize fields in your constructor
  2. clone can initialize a field, i.e. an array
like image 107
Jonas Eicher Avatar answered Sep 21 '22 15:09

Jonas Eicher


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.

like image 45
Yogendra Singh Avatar answered Sep 24 '22 15:09

Yogendra Singh