Cloning means creating a copy of the object. There is a way that we can create an exact copy of an object which is known as object cloning. To clone an object we use clone() method which is coming from Object class. Here we have to implement Clonable interface by the class whose object clone we want to create. If we are not trying to implement Cloneable interface, clone() method generates CloneNotSupportedException.
Let's see demo program on objet clonig for better clarity.

Example

class Employee implements Cloneable
{
int id;
String name;
Employee(int id,String name)
{
this.id=id;
this.name=name;
}
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}
public static void main(String[] args)
{
try
{
Employee e1=new Student18(102,"Trilochan");
Employee e2=(Employee)e1.clone();
System.out.println(e1.id+" "+e1.name);
System.out.println(e2.id+" "+e2.name);
}
catch(CloneNotSupportedException
{
}
}
}

Output

As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another. If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment