I understand how Java cloning works and the arguments against using it. Lets say I am dead set on using it anyway.
For the sake of convenience I would like to write a clone method for class Foo as follows:
@Override
public Foo clone(){
Foo f = (Foo)super.clone();
//Replace mutable fields
return f;
}
As far as I can tell this would be safe. However, I noticed that Cloneable classes in the API do not do this. Is there a reason for this and is it bad style?
The clone() is protected because it is not declared in the Cloneable interface. Because of this reason, the clone method becomes somewhat useless as it might make the copies of your existing data.
Therefore, while overriding the clone() method it is recommended to declare it public instead of protected so that it is access-able from a class in any location in the system. While overriding methods the method in the child class must not have higher access restrictions than the one in the superclass.
How to Handle CloneNotSupportedException. To avoid the CloneNotSupportedException , the Cloneable interface should be implemented by the class whose objects need to be cloned. This indicates to the Object. clone() method that it is legal to create a clone of that class and helps avoid the CloneNotSupportedException .
Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.
Back before Java 5, covariant return types weren't allowed at all, so Foo clone()
wouldn't even compile.
Since a lot of Cloneable
classes have been written a long time ago, that's probably the reason for majority of the cases.
I suspect that newer classes don't use it simply because clone()
is known to be quite a handful, and when people rarely do use it, they don't even think that they could cast it. They find some "how to implement clone()" question and write the code in the old fashioned way.
Object.clone()
creates a new object where all fields have the same value as the original. For fields of reference type, this means that the new field is simply a reference to the same object as the original. It does not clone
fields. Therefore in many cases, the default implementation would lead to shared data, which may be undesirable. For example, if ArrayList.clone()
used the default implementation, you would end up with two ArrayList
instances sharing the same backing array.
If all the fields of an object are immutable, it may be a good idea to simply cast the result of super.clone()
to the appropriate type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With