Java Object Cloning


In Java, object cloning is used to create an exact copy of an object. The java clone() method provide to clone an object.


When you want to create an object clone in a class.


  • You must implement the Cloneable interface.
  • You must override the clone() method from the Object class.
 Java Object Cloning

Syntax:

protected Object clone() throws CloneNotSupportedException  

Example:

 class A implements Cloneable
{  
    int sno;  
    String name;  
    A(int sno,String name)
    {  
        this.sno=sno;  
        this.name=name;  
    }  
    public Object clone()throws CloneNotSupportedException
    {  
        return super.clone();  
    }  
}
public class Objectclone
{
    public static void main(String args[])
    {  
        try
        {  
            A a=new A(1,"Onlinetpoint");  
            A b=(A)a.clone();  
            System.out.println(a.sno+" "+a.name);      
            System.out.println(b.sno+" "+b.name);  
        }
        catch(CloneNotSupportedException e)
        {
            System.out.println(e.getMessage());  
        }  
      
    }  
}

Differences between shallow copy and deep copy in java ?

Shallow Copy Deep Copy
Shallow copy is fast. Deep copy is slow.
The Cloned object and original object are not disjoint. The Cloned object and original object are disjoint.
If any changes in the cloned object which reflect the original object. If any changes in the cloned object which don't reflect the original object.
A clone method creates the shallow copy of an object by default. The override clone method which helps to create the deep copy of an object.
Shallow copy is less expensive. Deep copy is very costly.



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.