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)