what's the difference btn Clone an object and assign the reference

  • Thread starter Thread starter Vincent
  • Start date Start date
V

Vincent

Hey, I have a problem to understand the underlaying of
clone method. Hope someone can help me out.

Let's say,
clonedObject = originalObject.clone()

(syntax may be wrong, but you know what I mean, I hope )

Why can't I just do this, instead?

clonedObject = originalObject

Any comment is more than welcome.
Thanks in advance.

Vincent
 
Vincent,

The Clone() method is supposed to create a copy (although any given class
may implement it somewhat differently than you might expect), which should
end up being a separate object with the same attributes and/or state as the
original object. The "clonedObject = originalObject" does not create a
copy. Instead, both variables end up as references to the same object.

HTH,
Nicole
 
Think about it, cloning is making a copy of something. Suppose that you
have the following code.

object a = new MyObject();
object b = a

If you make changes to object "a", that same change will be reflected in "b"
simply because they both share the same memory location. They are the same
object.

Now, if I do

object a = new MyObject();
object b = MyObject.Clone();

Making changes to "a" has no effect on "b" because you now have two physical
objects in memory that share nothing (for the most part).
 
Thank you. I have one more question. Is Clone() method the
same as create a new instance. Someone says clone() is
much faster than doing new(). Why and when should I use
clone() and new().

Thanks again.

A guy who want to learn.
Vincent
 
Vincent,

Performance will differ between classes since, amongst other things, the
implementation of their constructors and Clone methods will differ. That
said, for most classes, instantiating a new object should be faster than
cloning. The only generalized exception to this is when both objects do
need to have the same data and retrieving this data from a source other than
the potentially cloneable object is quite expensive (e.g.: a slow-running
database query).

In general, you should be using cloning very rarely (i.e.: only when cloning
is what you really need to do). If you just need to create a new object
that will happen to be similar to an existing object, there's no compelling
reason to using cloning.

Also, you should be aware that a Clone method might not really be performing
what you might consider to be "cloning". If the object implements the
ICloneable interface, it should, but even that's no guarantee. Before you
even consider using cloning, I'd recommend you at least read up on the
ICloneable interface and the MemberwiseClone method of the Object class.

HTH,
Nicole
 
Back
Top