Joris Bleys said:
My intend was to use it for a deep cloning method in my containerclass. It
would call the clone() method for each element inside.
Mmm, this might be a solution. I could try to cast it to the Cloneable
interface. I'll try this right away.
Thanx for the advice !!
The Cloneable interface is just a marker, it has no
methods declared. The clone() method is protected.
Implementing the Cloneable interface does nothing
about the accessibility of the clone() method.
Unless a subclass has redefined with clone()
to be public access, your attempts will likely fail
miserably.
As others have said, your classes that are supposed
to know how to clone themselves should implement an
interface with the appropriate methods. You can
then use "instanceof" to decide if you can cast the
Object down to that interface, then use the method
to clone the underlying instance.
For this purpose, I use my own Replicatable interface.
public interface Replicatable
{
public abstract Replicatable replicate();
}
If I have a Fubar class that I want to be cloneable,
I do not implement Cloneable. I implement Replicatable
or a subinterface of Replicatable.
public interface ReplicatableFubar
extends Replicatable
{
public abstract Fubar replicateFubar();
}
public class Fubar
implements ReplicatableFubar
{
// implement the methods here
public ReplicateFubar replicateFubar()
{
return /* whatever you need to do to create a copy of this */;
}
public Replicate replicate()
{
return replicateFubar();
}
}
Now, in my code, when I have a known reference to a Fubar
object, I can use fubar.replicateFubar() to get a copy
of the Fubar object. When I only have a reference to
a Replicatable object, I can use replicatable.replicate()
to make another Replicatable object of the same underlying
type. This is polymorphism and it works very well.
The benefit of using a Replicatable interface is that
the underlying object decides what parts of its instance
will be replicated. Cloning can cause dangling references
and many other problems, if its not implemented exactly
right. So, to avoid confusion about what cloning is or
is not, I use Replicate.
Two cents worth. Your mileage may vary.