Cloning in java


When we copy one object into another object, that process is called cloning.
We achieve cloning by implementing Cloneable interface.

Class Employee
{
   String name;
   String id;
   Department depart;
   Public Employee(String name, String id, Department depart)
    {
      this.name = name;
      this.id = id;
      this.depart = depart;
    }
} 

Class Department
{
   String name;
   String id;
   Public Department(String name, String id)
    {
        this.name = name;
        this.id = id;
    } 
}
Class MainClass
{
 Public statis void main(String[] args)
 {
     Employee emp1 = new Employee("Rahul", "123",new Department("12", "OLPS"));
     Employee emp2 = (Employee)emp1.clone();
     System.out.println("Employee 1 : "emp1.name + emp1.id+ emp1.depart.id+ emp1.depart.name);
     System.out.println("Employee 2 : "emp2.name + emp2.id+ emp2.depart.id+ emp2.depart.name);	
  }
}


Output:
Employee 1: Rahul 123 12 OLPS
Employee 2: Rahul 123 12 OLPS

Note:

  • Main benefit of clone() method is that it reduces the line of code to copy one object to another and its fast in processing.
  • Cloneable is a marker interface.
  • Method clone() is inside the Object class.
  • If we call clone() method without implementing the Cloneable interface then it will throw exception CloneNotSupportedException.