Clone method has puzzled me ever since I have started doing serious coding in java. There are two interesting facts about it:
Let me explain,
"The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. Unfortunately it fails to serve this purpose ... This is a highly atypical use of interfaces and not one to be emulated ... In order for implementing the interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable and largely undocumented protocol
References : http://stackoverflow.com/questions/1138769/why-is-the-clone-method-protected-in-java-lang-object
- Its declared as protected
- Its declared in java.lang.Object class instead of Cloneable interface
Let me explain,
- Object.clone() will not do what you want with your custom-defined class. This is why it has been made protected.
- If you have Customclass implements Cloneable. You override clone() with "public Customclass clone()"
- If you have CustomInterface extends Cloneable and some CustomClasses implementing CustomInterface: simply define "public CustomInterface clone();" in the interface and every method using CustomInterface objects will be able to clone them, no matter their Customclass-class.
"The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. Unfortunately it fails to serve this purpose ... This is a highly atypical use of interfaces and not one to be emulated ... In order for implementing the interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable and largely undocumented protocol
References : http://stackoverflow.com/questions/1138769/why-is-the-clone-method-protected-in-java-lang-object
No comments:
Post a Comment