3

I wanted to ask cause i'm fairly new at this , is this the correct way of making a deep copy of the Document Object , i don't know if I implemented correctly the copying of the fields.

package model;

public class Document implements Cloneable {
    //fields
    private String author;
    private String date;
    private double versionID;
    private String contents;


    public Document(String author,String date,double versionID,String contents) {
         this.author=author;
         this.date=date;
         this.versionID=versionID;
         this.contents=contents;        
    }

    //getters-setters

    }
    //making the deep-copy clone all obj ref to Document
    @Override
    public Object clone() throws CloneNotSupportedException {
        Document doc =(Document)super.clone();
        doc.author=this.author;
        doc.date=this.date;
        doc.versionID=this.versionID;
        doc.contents=this.contents;

        return doc;
    }   

}
DavidDunn
  • 143
  • 1
  • 12
  • 1
    You may want to use https://codereview.stackexchange.com/ – MWB Apr 13 '19 at 16:34
  • As Effective Java states: "Override clone judiciously". You should just use a standard copy constructor in most of the cases instead. – Glains Apr 13 '19 at 17:19

1 Answers1

1

Your object only has primitive types and immutable strings, so Document doc =(Document)super.clone(); is enough and you dont have to do the separate assignments. But this is a bit risky, since should you ever add a mutable object to the fields, not doing a separate copy of that object will cause problems. There are already extended discussions also on using some existing libraries to do deep copies, e.g as in here: How do you make a deep copy of an object in Java?

awagen
  • 236
  • 2
  • 8
  • i see , i dont think ill add something no . I will work only with those string types . I will leave it like that then and I hope it doesn't cause me any trouble. – DavidDunn Apr 13 '19 at 16:57