Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use the clone() method in Java?

Tags:

java

clone

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?

like image 471
Abhisek Avatar asked Apr 27 '11 09:04

Abhisek


People also ask

What is clone and where did you use in java?

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().

Why is the clone () method protected in java Lang object?

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'.

What is the purpose of the following code 1 protected Object clone () throws Clonenot Supportedexception?

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.


1 Answers

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); 
like image 148
Andreas Dolk Avatar answered Oct 14 '22 17:10

Andreas Dolk