Home>

We need to make a copy method (not through clone, but manually) of the object.

obj1= obj2;does not fit, since it will just throw the link and that's it (the class is a reference type).

It is necessary that the 2 object be independent from the second, i.e. copied it -and it is possible to change it without touching the first object.

  • Answer # 1

    Something like this can be:

    public class MyObject {
          private int field1;
          private String field2;
          private List <
    String >
     field3= new ArrayList <
    String >
    ();
          //copy constructor
          public MyClass (MyClass other) {
               //copy all fields of the class
    here
               //primitive types are passed by value
               this.field1= other.field1;
               //for the rest, use their copy constructors
               this.field2= new String (other.field2);
               this.field3= new ArrayList <
    String >
    (other.field3);
          }
          //method copying object
          public MyClass copy () {
               return new MyClass (this);
          }
    }
    

    There are 2 ways, you can call it like this:

    MyObject obj1= new MyObject ();
    //...
    MyObject obj2= new MyObject (obj1);
    //or so
    MyObject obj2= obj1.copy ();
    

    Here read, the best practices of this business here...

  • Answer # 2

    Something like this can be:

    public class MyObject {
          private int field1;
          private String field2;
          private List <
    String >
     field3= new ArrayList <
    String >
    ();
          //copy constructor
          public MyClass (MyClass other) {
               //copy all fields of the class
    here
               //primitive types are passed by value
               this.field1= other.field1;
               //for the rest, use their copy constructors
               this.field2= new String (other.field2);
               this.field3= new ArrayList <
    String >
    (other.field3);
          }
          //method copying object
          public MyClass copy () {
               return new MyClass (this);
          }
    }
    

    There are 2 ways, you can call it like this:

    MyObject obj1= new MyObject ();
    //...
    MyObject obj2= new MyObject (obj1);
    //or so
    MyObject obj2= obj1.copy ();
    

    Here read, the best practices of this business here...