Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Object Cloning

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 367
    Comment on it

    Object Cloning:

    Cloning means to create exact copy of an existing object. To clone a object we have to implement  java.lang.Cloneable interface by that class whose object will be cloned. clone() method is defined in Object class.

    Example:

        class ObjClone implements Cloneable{  
        int rollno;  
        String name;  
          
        ObjClone(int rollno,String name){  
        this.rollno=rollno;  
        this.name=name;  
        }  
          
        public Object clone()throws CloneNotSupportedException{  
        return super.clone();  
        }  
          
        public static void main(String args[]){  
        try{  
        ObjClone s1=new ObjClone(101,"sam");  
          
        ObjClone s2=(ObjClone)s1.clone();  // cloning s1 object
          
        System.out.println(s1.rollno+" "+s1.name);  
        System.out.println(s2.rollno+" "+s2.name);  
          
        }catch(CloneNotSupportedException c){}  
          
        }  
        }  
    Output:101 sam
           101 sam

    In the above  example we are cloning the object of class ObjClone by using clone() method of Cloneable interface.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: