Domanda

I read lots of threads about the clone() method of Object and the Cloneable Interface but I couldn't find a legitimate answer to my question. Long story short:

What I figured out is that Object has a method clone() which can "magically" clone your object. But you can't use that method without implementing Cloneable Interface because this interface allows Object to use the clone() method. So why did they do that? Why shouldn't every object be cloneable from the start?

È stato utile?

Soluzione

Cloneable makes sense for some mutable data.

It doesn't make sense for

  • immutable data
  • where you might need a shallow or a deep copy.
  • objects which represent resources such as threads, sockets, GUI components
  • singleton and enumerated types
  • mutable state where data should only be copied to avoid creating new objects.

Some coding styles suggest keeping new mutable data object to a minimum. Cloneable doesn't suit all situations and if you made all objects Cloneable you wouldn't be able to turn it off cleanly.

Note: There are many projects which avoid using Cloneable anywhere.

Altri suggerimenti

Because if every object ( including the object of user-defined class) can be cloned just by using clone method then it might lead to the unintentional mutation of the original object being cloned as clone provides shallow copy of the original object. For example:

class MyClass
{
  private int val;
  public void setVal(int i)
  {
    this.val = i;
  }
  public int getVal()
  {
    return this.val;
  }
  public static void main(String st[]) throws Exception
  {
    ArrayList<MyClass> ar = new ArrayList<MyClass>();
    MyClass mc = new MyClass();
    mc.setVal(50);
    ar.add(mc);
    ArrayList<MyClass> copy =(ArrayList) ar.clone();//Since ArrayList is cloneable
    copy.get(0).setVal(10);
    System.out.print(ar.get(0).getVal());//it shows 10 instead of 50!!
  }
}

Hence we see that Cloning may lead to inconsistency in the internal state of original object being copied. So to avoid such scenario , the prevalence is given to the programmer while defining the class whether he/she wants the object of that class to be cloned or not.

Clone means to create the new copy of the object and doesn't share the memory location as happened in case of assignment operator.

Example

         MyObject obj1 = new MyObject();
         obj2 = obj1;

Here, in this case any changes you make to obj1 will reflect in obj2 and vice versa because obj2 holds the memory location of obj1.

but if you don't want, the change made in obj2 to be seen in obj1, or any change made in obj1 to be seen in obj2, then you perform Cloning. In this case both objects will have different memory location.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top