Copy Constructor and Assignment Operator

advertisement
Are there copy constructor and assignment constructor in java?
There is such a thing as a copy constructor in Java, but it does not play the special role that
such constructors do in C++. A copy constructor in Java is just like any other constructor: you
call it with new.
public class A {
private int x;
public A(int x) { this.x = v; }
public A(A that) { this.x = that.x; }
}
...
A a1 = new A(5);
A a2;
a2 = new A(a1);
...
There are no assignment constructors, or anything much like them, in Java. That is because
Java does not have operator overloading. The assignment operation (=) is always a shallow
assignment, or scalar assignment if you prefer, and you NEVER have to doubt that. I've
gotten in plenty of trouble with C++ code that used fancy copy constructors and overloaded
assignment operators!
Java does have the notion of a clone (copy) method. Any object can support the clone()
method; by convention the method implementation is supposed to perform a deep copy
of the object on which it is called, and return the copy. Of course, there are difficulties with that,
too.
Download