0

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; 
    }
Cipollino
  • 37
  • 1
  • 7
  • 2
    What does the Example constructor do - just save those values in parameter1 and parameter2? Unless it deep clones those parameters then I think this is just a shallow clone of Example. – Rup Dec 29 '19 at 01:05
  • @Rup: Yes exactly - see the edit. Since parameter1 and parameter2 are primitive types, what would deep cloning them mean? – Cipollino Dec 29 '19 at 01:22
  • 1
    [How to properly override clone method?](https://stackoverflow.com/questions/2326758/how-to-properly-override-clone-method) – Abra Dec 29 '19 at 01:33

1 Answers1

3

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.

Anthony Cathers
  • 302
  • 2
  • 7
  • Ok, so to make sure I have understood you correctly: let's say parameter1 was not primitive. My clone would then be a new object (i.e. have a own, new reference) but its parameter1-attribute would reference the same object that is referenced by its 'parent's' (sorry if this is not the correct term) parameter1-attribute and that is why it would be only a shallow copy, right? – Cipollino Dec 29 '19 at 01:34
  • 1
    Yes, java is pass by value but with Objects it passes the value of the reference. So you're just copying that value of the reference over, so both fields will still refer back to the same Object – Anthony Cathers Dec 29 '19 at 01:40