Java-Object Cloning

Object Cloning

The clone method generates a duplicate copy of the object on which it is called. Only classes that implement the Cloneable interface can be cloned. The Cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy of an object (that is, a clone) to be made. If you try to call clone( ) on a class that does not implement Cloneable, a CloneNotSupportedException is thrown. A clone is simply an exact copy of the original. Notice(below program) that the object returned by clone( ) must be cast into its appropriate type (Data).

Program

00

Program Source

class Data implements Cloneable{
    
    int data1;
    int data2;
    
    public Data cloning()
    {  
        try{
            return (Data)super.clone();  
        }catch (CloneNotSupportedException cns) {
            System.out.println("Cloning Error");
            return this;
        }
    }  
}

public class Javaapp {

    public static void main(String[] args) {
        
        Data d1 = new Data();
        d1.data1 = 50;
        d1.data2 = 100;
        System.out.println("d1.data1 = "+d1.data1);
        System.out.println("d1.data2 = "+d1.data2);
        
        Data d2 = d1.cloning();
        System.out.println("d2.data1 = "+d2.data1);
        System.out.println("d2.data2 = "+d2.data2);
    }
}

Leave a Comment