Friday, 19 December 2014

What is Clone() method ( Object Cloning ) in java ?

The clone() method :

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(exact copy) 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 gives CloneNotSupportedException.  The clone() method is defined in the Object class.

Syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException

Que: Why use clone() method ?

Ans: The clone() 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.

Example of clone() method (Object cloning):

class Employee implements Cloneable{
int eid ;
String ename;
Student(int eid,String ename){
this.eid=eid;
this.ename=ename;
  }
public Object clone()  throws CloneNotSupportedException{

return super.clone();
}
public static void main(String []args){

try{
Employee e1=new Employee(111,"vishwa");
Employee e2=(Employee)e1.clone();
System.out.println(e1.rollno+" "+e1.name);
System.out.println(e2.rollno+" "+e2.name);
  }
catch(CloneNotSupportedException c)  {     }
  }
}

Output: 111 vishwa
                111 vishwa

No comments:

Post a Comment