Java Copy constructor with "this"

I have a fairly general question about java. I want to know if there is an easy way to recreate this C ++ code in java:

class A 
{

public:
  int first;
  int second;

  A(const A& other) {
    *this = other;
  }

...
}

      

So basically a copy constructor where you can pass an existing object A to a new object a in the constructor and it will copy the content and build an exact copy of the existing object A.

trying

class A {
  int first;
  int second;

  public A(A other){        
    this = other;
  }
 ...
}

      

sadly not working as eclipse tells me that "this" is not allowed on the left side of the assignment as it is not a variable.

I know I would achieve the same results:

class A {
      int first;
      int second;

      public A(A other){        
        this.first = other.first;
        this.second = other.second;

      }
     ...
    }

      

But I would like to know if there is an easier way as sometimes you have a few more class variables.

Thanks in advance!

+3


source to share


3 answers


There is no simpler way defined by the Java language, however there are a few complex methods that can allow you to do this:

  • Clone an object via serialization: http://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html : precondition - all class properties in the structure must either be primitive , or the classes are marked asSerializable

  • toString () -> fromString (String s) - the corresponding methods should be implemented
  • POJOs and beans can be easily reconstructed using XML / JSON intermediate representation with available libraries like Jackson etc.


As far as I know, the most efficient way after direct mapping is the serialization mechanism.

+1


source


What you have in the third version of this class is legal java, which does exactly the same as your C ++ class, however I don't think there is an easier way than what you wrote.



+1


source


The best way to recycle your code:

class A {

   int first;
   int second;

   public A(int f, int s){        
      this.first = f;
      this.second = s;
   }

   public A(A a){
      this(a.first, a.second); // id use getters instead ofc.
   }
}

      

+1


source







All Articles