Cloning in Java

Introduction

In Java, cloning means creating a duplicate of an object. It is very useful in Java. When we want to make some changes in our object but we do not want to disturb our previous object then we use cloning in Java.

Cloning in Java

We can define cloning in Java as an aspect of creating a duplicate of the object. We use the clone( ) method in Java to do that. When we want to create a clone of the object of a specific class then we need to implement the interface java.lang.Cloneable in Java. Basically we do cloning in Java when we want to create an identical object to an existing object on which we can do some changes without affecting the original object. This is the sole purpose of cloning in Java. This is required for the creation of the clone in Java. We can also make a new object by the new keyword in Java, but it is very time-consuming process relative to the cloning in Java. That is why it is very important in Java.

Syntax

protected Object clone() throws CloneNotSupportedException 

Example

package demo;

public class Demo implements Cloneable

    int id; 

    String deptt;

    Demo(int id,String deptt)

    { 

        this.id=id; 

        this.deptt=deptt; 

    } 

    protected Object clone()throws CloneNotSupportedException

    { 

        return super.clone(); 

    } 

    public static void main(String args[])

    { 

        try

        { 

            Demo d=new Demo(1091005,"C.S."); 

            Demo d1=(Demo)d.clone(); 

            System.out.println(d.id+" "+d.deptt); 

            System.out.println(d1.id+" "+d1.deptt); 

        }

        catch(CloneNotSupportedException c)

        {

           

        } 

    } 

}

Output

object cloning

Copy Constructor in Java

In Java, a copy constructor is also used to copy the object. It captures objects of its own type as a single parameter in Java. In Java, we do not have a default copy constructor. Copy constructors are very easy to implement in Java.

Example

package demo;

public class Demo

{

    private int len;

    private int bd;

    private int rad;

    Demo(int a,int b)

    {

        len=a;

        bd=b;

    }

    int area()

    {

        return len*bd;

    }

    Demo(Demo obj)

    {

        len=obj.len;

        bd=obj.bd;

    }

    public static void main(String args[])

    {

        Demo d=new Demo(10,15);

        Demo d1=new Demo(d);

        System.out.println("Area of d = "+d.area());

        System.out.println("Area of d2 = "+d1.area());

 

    }

}

Output

copy constructor

Summary

This article has explained cloning in Java.

Up Next
    Ebook Download
    View all
    Learn
    View all