Friday, January 30, 2026
HomeLanguagesJavaCloning in java

Cloning in java

Object cloning means to create an exact copy of the original object.

If a class needs to support cloning, it must implement java.lang.Cloneable interface and override clone() method from Object class. Syntax of the clone() method is :

protected Object clone() throws CloneNotSupportedException

If the object’s class doesn’t implement Cloneable interface then it throws an exception ‘CloneNotSupportedException’ .

 




// Java code for cloning an object
  
class Test implements Cloneable
{
    int a;
    int b;
  
    // Parameterized constructor
    Test(int a, int b)
    {
        this.a = a;
        this.b = b;
    }
  
    // Method that calls clone()
    Test cloning()
    {
        try
        {
            return (Test) super.clone();
        }
        catch(CloneNotSupportedException e)
        {
            System.out.println("CloneNotSupportedException is caught");
            return this;
        }
    }
}
  
class demo
{
    public static void main(String args[])
    {
        Test obj1 = new Test(1, 2);
        Test obj2 = obj1.cloning();
        obj1.a = 3;
        obj1.b = 4;
        System.out.println("Object2 is a clone of object1");
        System.out.println("obj1.a = " + obj1.a + " obj1.b = " + obj1.b);
        System.out.println("obj2.a = " + obj2.a + " obj2.b = " + obj2.b);
    }
}


Output :

Object2 is a clone of object1
obj1.a = 3 obj1.b = 4
obj2.a = 1 obj2.b = 2

 
This article is published by Mehak Narang.

 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS