javaclone

object cloning with out implementing cloneable interface


to clone the object do i need to implement 'cloneable' interface. because here my class is a jar file(i mean API). so i can't edit the class. i heard that all classes are extends the base object class and this object class implements cloneable interface. does that mean can we directly clone the object with out implementing the interface. if so in my eclipse i am not getting any option to clone the object. is there any other way to clone the object without implementing the cloneable interface. please explain.


Solution

  • The Java Object class does not implements the Cloneable interface. It does however have the clone() method. But this method is protected and will throw CloneNotSupportedException if called on an object that does not implement the Cloneable interface. So if you cannot modify the class you want to clone you're out of luck and will have to find another way to copy the instance.

    It should be note however that the clone system in Java is full of holes and generally not used anymore. Check out this interview with Josh Bloch from 2002 explaining a few of the issues.