Switching clones with and without cloning

I read javadoc for Object and Cloneable and just don't β€œget” something. Can someone explain to me the performance and / or functional differences of the two following examples:

 public class Widget { @Override public Widget clone() { // ... return a clone of this Widget } } 

.. and:

 public class Widget implements Cloneable { @Override public Widget clone() { // ... return a clone of this Widget } } 

Since Cloneable has no methods attached to it and gives you access to the Object protected clone () method, does it make sense to ever implement it first, seeing that you will eventually have to write your own (safe) clone code () anyway? Thanks in advance for any clarification / input.

+6
source share
2 answers

This is a contractual obligation .

A call to the object cloning method for an instance that does not implement the Cloneable interface throws an exception. A CloneNotSupportedException is thrown.

Even though there are no methods for overriding, you still implement the interface you are in. In this case, you assume all that is associated with his subsequent contract. This forces you to consciously implement the clone() method, thereby making the behavior explicit.

+5
source

a) Cloning causes an extralinguistic way of constructing objects - without constructors.

b) Cloning requires that you somehow handle a CloneNotSupportedException - or to bother client code to handle it.

c) The benefits are small - you just don't have to manually write a copy constructor. So use Cloneable judiosly. This does not give you sufficient advantages in comparison with the efforts that you need to apply so that everything is in order.

About Java cloneable

0
source

Source: https://habr.com/ru/post/899323/


All Articles