Why and when do I need to use clone?

P

PJ

I need to make copies for a class A. Do I have to implement Cloneable
and use clone? Can I just make a method called copy, which returns A,
and use it to do copy?

Thanks!
 
S

Stefan Schulz

I need to make copies for a class A. Do I have to implement Cloneable
and use clone? Can I just make a method called copy, which returns A,
and use it to do copy?

You can create a copy method. Usually, this will even be preferable to
the inherently obscure and counter-intuitive clone() mechanism
 
C

Chris Smith

PJ said:
I need to make copies for a class A. Do I have to implement Cloneable
and use clone? Can I just make a method called copy, which returns A,
and use it to do copy?

If you implement a copy() method, then you have to take complete
responsibility for ensuring that the copy() method is complete and
correct. In trivial cases (specifically, in classes that will never be
subclassed) this isn't too tough. But you may as well call the method
clone() instead of copy(). If you implement clone, it's a good idea to
implement the Cloneable interface as well, just to make it clear that
the class can be cloned.

In cases with subclasses (or that's non-final, and therefore may gain
subclasses later), this task is fairly difficult, and you'll want to
look into using the clone() method fully. This means implementing
Cloneable and delegating first to the superclass (and ultimately to
Object) before patching up with any additional cloning work that's
needed in this class.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,263
Messages
2,571,064
Members
48,769
Latest member
Clifft

Latest Threads

Top