What are the advantages and disadvantages of object cloning?


Advantage of Object Cloning

  • You don't need to write lengthy and repetitive codes. Just use an abstract class with a 4- or 5-line long clone() method.
  • It is the easiest and most efficient way of copying objects, especially if we are applying it to an already developed or an old project. Just define a parent class, implement Cloneable in it, provide the definition of the clone() method and the task will be done.
  • Clone() is the fastest way to copy the array.

Disadvantage of Object Cloning

  • To use the Object.clone() method, we have to change many syntaxes to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone(), etc.
  • We have to implement the Cloneable interface while it does not have any methods in it. We have to use it to tell the JVM that we can perform a clone() on our object.
  • Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
  • Object.clone() does not invoke any constructor, so we do not have any control over object construction.
  • If you want to write a clone method in a child class, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
  • Object.clone() supports only shallow copying, but we will need to override it if we need deep cloning.
0 answers