Java Object Cloning

    Object Cloning

    The object cloning will allow you to create an exact object copy. You can use the clone() method from the class Object to create an object’s clone. If you want to create an object clone for any class then that class have to implement java.lang.Cloneable interface. CloneNotSupportedException will get raised by the clone() method if you do not implement the interface. This Clone() method is defined within the Object class.

    Clone method syntax-

    protected Object clone() throws CloneNotSupportedException  

    Clone() method usage-

    Using the clone() method will save you the extra processing task that will be done while using the new keyword for object creation.

    Advantages-

    clone() method allows you to copy the objects in a simple way. Though it has some design issue still is a very popular method to create the object’s copy.

    • Your efforts will be saved for writing lengthy codes again and again.
    • This method will be beneficial if we are applying it to the already existing project. For this, you have to define a class with the cloneable in it.
    • You can copy the array using the clone() method is the most efficient way.

    Disadvantages-

    Below is the list of the disadvantages-

    • This way is easy but you have to make many syntax changes to your code. Like defining clone() method, implementing the Cloneable interface, handling an exception, and calling the Object.clone() method.
    • The cloneable interface does not have any methods to implement still we have to implement it to tell the JVM that the clone can be performed for the object.
    • Object.clone() is defined as protected so that we have to create our own clone() to call Object.clone() from it.
    • If you are using the clone() method in the child class then you have to define the clone() method in all the superclasses for that class.

    Example-

    //package Simple_pack;
    
    //import demo_pack.*;
    
    class Simple implements Cloneable{
    
    int var;
    
    Simple(int var){
    
    this.var=var;}
    
    
    
    public Object clone()throws CloneNotSupportedException{  
    
    return super.clone();  
    
    }  
    
    public static void main(String args[]){  
    
    try{
    
    Simple s=new Simple(100);
    
    Simple ss=(Simple)s.clone();
    
      
    
    System.out.println(s.var);
    
    System.out.println(ss.var);
    
      }  
    
    catch(CloneNotSupportedException c){
    
    }  
      
    }  
    
    } 

    Output-