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 a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.