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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 170
    Comment on it

    Whenever we want to create an exact copy of an object, object cloning is used. So, clone() method of Object class is used to clone an object.
    The java.lang.Cloneable interface must be implemented by the class to create object clone. And If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
    The clone() method is defined in the Object class.
    Syntax of the clone() method is as follows:
    protected Object clone() throws CloneNotSupportedException

    The clone() method saves the extra processing task requires for creating exact copy of an object.
    Example of clone() method i.e.Object cloning

    class Student implements Cloneable{  
    int rollno;  
    String name;  
    
    Student(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{  
    Student s1=new Student(101,"pranav");  
    
    Student s2=(Student)s1.clone();  
    
    System.out.println(s1.rollno+" "+s1.name);  
    System.out.println(s2.rollno+" "+s2.name);  
    
    }catch(CloneNotSupportedException c){}  
    
    }  
    }  
    

    Output:101 pranav
    101 pranav

 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: