Search code examples
javaclone

Simple deep copying method in Java


I am trying my hand at deep copying in Java. So far I have implemented the following method in the class (Example) whose objects I would like to get deep copies of (parameter1 and parameter2 being the parameters needed by the constructor of the Example-class to create an object of the latter):

public Example clone(){
   Example clone = new Example(this.parameter1, this.parameter2);
   return clone;
   }

So basically I clone an object by calling the constructor of the corresponding class and by using its current attributes as parameters for that constructor. My problem is that this seems a bit too simple to be true. Especially since the solutions I looked up online were much more complex. So I'm wonderin what the hook is with my method. Any hint/explanation will be greatly appreciated.

EDIT: This is the constructor for the Example-class:

public Example(double parameter1, double parameter2){
    this.parameter1 = parameter1;
    this.parameter2 = parameter2; 
    }

Solution

  • With primitives it is relatively simple. But if you had any fields that were not primitive, just using that copy constructor would only result in a shallow copy of that object. Meaning you would be using the same object for your field between the classes.