Why do we use the clone()
method in Java? (Please give the answer in respect of memory constraint.) Will that reduce memory usage? If yes, then how? Will that reduce the effect of memory leak?
The clone method creates an exact copy of an object for which it has been invoked in a field-by-field assignment order and will return the new object reference. One thing that you must remember, in Java, the objects which implement the clone interface which is a marker interface is allowed to use the clone().
clone() method is protected i.e. accessed by subclasses only. Since object is the parent class of all sub classes, so Clone() method can be used by all classes infact if we don't have above check of 'instance of Cloneable'.
Class CloneNotSupportedException Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.
Apart from do not use clone, implement a copy constructor, you asked about memory constraints.
The idea of cloning is to create an exact duplicate of the cloned object. So in worst case, you use twice the amount of memory afterwards. Practically - a bit less, because Strings are often interned and will (usually) not be cloned. Even though it's up to the implementor of the clone method/copy constructor.
Here's a short example of a class with a copy constructor:
public class Sheep { private String name; private Fur fur; private Eye[2] eyes; //... // the copy constructor public Sheep(Sheep sheep) { // String already has a copy constructor ;) this.name = new String(sheep.name); // assuming Fur and Eye have copy constructors, necessary for proper cloning this.fur = new Fur(sheep.fur); this.eyes = new Eye[2]; for (int i = 0; i < 2; i++) eyes[i] = new Eye(sheep.eyes[i]); } }
Usage:
Sheep dolly = getDolly(); // some magic to get a sheep Sheep dollyClone = new Sheep(dolly);
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