Monday, March 3, 2014

Object Cloning in Java



Object Cloning in Java

The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. 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  

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)

  class Strudent implemants 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,"kumar");
         Student s2 = (Student)s1.clone();
         System.out.println(s1.rollno+" "+s1.name);
         System.out.println(s2.rollno+" "+s2.name);
   }
   Catch(CloneNotSupportedException c){    
    }
   }
Output:
             101 kumar
             101 kumar

No comments:

Post a Comment