mark wrote:
> what is the equivalent in java of "copy constructor" that is used in C++ ?
>
Mark,
Xarax's answer is right, but a little terse. I'll expand a bit.
In C++, a variable can be either an object or a pointer to the object.
In Java, that's not true; a variable, if it has anything to do with an
object at all, is a reference that points to that object. One of the
several problems that copy constructors are meant to solve in C++ is
what happens when you make a copy of a variable (e.g., via pass-by-value
to a method) that is an object. That problem doesn't arise in Java,
because variables can only be references, and it's always obvious how to
copy a reference (and the result points to the same object as the
original). So there's no copying of objects done "behind the scenes" in
Java, as would be the case with C++.
However, programmers in C++ also use copy constructors to explicitly
make a copy of an object. This is a need that exists in Java as well,
and there is a way to deal with it: the clone() method. Java provides
clone() as a replacement for copy constructors because copy constructors
can be very difficult to use when polymorphism is prevalent in the
design; you don't need to know the exact concrete subclass of an object
in order to clone() it, whereas you do in order to copy it correctly
using a copy constructor.
The problem with clone() is that it was declared protected in Object,
meaning that you need to specifically allow cloning when you define a
class by overriding it with a public version. You'd additionally need
to meet the contract of the clone() method, of course, and the easiest
way to do this is to implement the Clonable interface and start out by
calling Object's clone() implementation before making any needed
modifications on the result. A convenient side-effect of Object.clone()
-- in addition to creating the right class of object for you -- is that
it provides a shallow copy of fields, but any deep copying needs to be
done explicitly.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation