Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem with ‘=’ Operator
3.
The Clone Method
4.
Types of Cloning in Java
5.
Shallow Cloning
5.1.
Program:
5.2.
Output:
6.
Deep Cloning
6.1.
Program:
6.2.
Output:
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Object Cloning in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

You must have faced a situation in which you need to copy the contents of an object to a new object in such a way that changing the variables of any one object does not affect the other. As you have noticed, simply using the assignment operator does not provide the desired result.

In this blog, we will discuss the clone() method of Object class to achieve the required results.

Problem with ‘=’ Operator

When we copy an object to a new object using the ‘=’ (assignment) operator, it simply creates a copy of reference variables. The original and the copy are references to the same object. Any change in one object affects the other as well, which is not desired.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

The Clone Method

The clone() method is used to solve the issue and achieve the desired results. We must use the clone() method if we want a copy to be a new object that starts off identical to the original but whose state can change over time, independent of the original object.

The clone() method eliminates the need for additional processing when making an exact copy of an object. It will take a lot of effort if we do it with the new keyword, therefore we may utilise object cloning instead. The clone method creates an exact copy of an object for which it has been invoked in a field-by-field assignment order and will return the new object reference.

The Cloneable interface must be implemented by a class whose object clone to create. If we do not implement Cloneable interface, clone() method generates CloneNotSupportedException.

Types of Cloning in Java

Cloning in Java can be grouped into two categories:

  1. Shallow Cloning
  2. Deep Cloning

Shallow Cloning

Shallow Cloning is a term used in Java to describe the cloning process that uses the clone() method. In shallow cloning, if the original object has references to other objects as fields, only those references will be cloned rather than a new object being created. In other words, if you change the parameters of objects that are referenced in the original object, it will get reflected in both the objects (original and cloned one). As a result, shallow cloning is constrained by the original object. We will now see an example to see the above concept in action.

Program:

class Employee {

 String name;
 int salary;

 public Employee(String name, int salary) {
   this.name = name;
   this.salary = salary;
 }
}

class Company implements Cloneable {

 int companyID;
 String companyName;
 Employee Employee;

 public Company(int companyID, String companyName, Employee Employee) {
   this.companyID = companyID;
   this.companyName = companyName;
   this.Employee = Employee;
 }

 //Default version of clone() method
 protected Company clone() throws CloneNotSupportedException {
   return (Company) super.clone();
 }
}

public class ShallowCloning {

 public static void main(String[] args) {
   Employee emp = new Employee("Rahul", 50000);

   Company company1 = new Company(0, "CodingNinjas", emp);

   Company company2 = null;

   try {

     //Creating a clone of company1 and assigning it to company2
     company2 = (Company) company1.clone();
     company2.companyID = 1;

   } catch (CloneNotSupportedException e) {
     e.printStackTrace();
   }

   //Printing Details of company1
   System.out.println("Details of Company 1: \n");
   System.out.println("Id: " + company1.companyID);
   System.out.println("Name: " + company1.companyName);
   System.out.println("Course Id: " + company1.Employee.name + "\n\n");

   //Printing Details of company2
   System.out.println("Details of Company 2: \n");
   System.out.println("Id: " + company2.companyID);
   System.out.println("Name: " + company2.companyName);
   System.out.println("Course Id: " + company2.Employee.name+"\n\n");

   //Changing the salary of employee of company2
   System.out.println("Changing the salary of employee of company 2 to 60,000");
   company2.Employee.salary = 60000;

   System.out.println("Salary of Employee of company2: "+company2.Employee.salary+"\n\n");

   //This change will be reflected in original 'company1'
   System.out.println("Updated Details of Company 1:");
   System.out.println("Name of employee of Company 1: "+company1.Employee.name);
   System.out.println("Salary of employee of Company 1: "+company1.Employee.salary);
 }
}

Output:

Details of Company 1: 

Id: 0
Name: CodingNinjas
Course Id: Rahul


Details of Company 2: 

Id: 1
Name: CodingNinjas
Course Id: Rahul

Changing the salary of employee of company 2 to 60,000
Salary of Employee of company2: 60000

Updated Details of Company 1:
Name of employee of Company 1: Rahul
Salary of employee of Company 1: 60000


Practice by yourself on java online compiler.

Deep Cloning

Deep Cloning is a term used in Java to describe the cloning process that uses the clone() method with added functionality. In deep cloning, if the object to be cloned references other objects as field parameters, those objects are cloned as well. In other words, changes in the parameters of objects that are referenced in the original object will not get reflected in the other one. As a result, deep cloning is not constrained by the original object. This makes the cloned object independent of the original object and any changes made in any of the objects won’t be reflected on the other. We will now see an example to see the above concept in action.

Program:

class Employee implements Cloneable {

 String name;
 int salary;

 public Employee(String name, int salary) {
   this.name = name;
   this.salary = salary;
 }

 protected Employee clone() throws CloneNotSupportedException {
   return (Employee)super.clone();
 }
}

class Company implements Cloneable {

 int companyID;
 String companyName;
 Employee Employee;

 public Company(int companyID, String companyName, Employee Employee) {
   this.companyID = companyID;
   this.companyName = companyName;
   this.Employee = Employee;
 }

 //Default version of clone() method
 protected Company clone() throws CloneNotSupportedException {
   Company copy =  (Company) super.clone();
   copy.Employee = copy.Employee.clone();
   return copy;
 }
}

public class ShallowCloning {

 public static void main(String[] args) {
   Employee emp = new Employee("Rahul", 50000);

   Company company1 = new Company(0, "CodingNinjas", emp);

   Company company2 = null;

   try {
     //Creating a clone of company1 and assigning it to company2
     company2 = (Company) company1.clone();
     company2.companyID = 1;
   } catch (CloneNotSupportedException e) {
     e.printStackTrace();
   }

   //Printing Details of company1
   System.out.println("Details of Company 1: \n");
   System.out.println("Id: " + company1.companyID);
   System.out.println("Name: " + company1.companyName);
   System.out.println("Course Id: " + company1.Employee.name + "\n\n");

   //Printing Details of company2
   System.out.println("Details of Company 2: \n");
   System.out.println("Id: " + company2.companyID);
   System.out.println("Name: " + company2.companyName);
   System.out.println("Course Id: " + company2.Employee.name + "\n\n");

   //Changing the salary of employee of company2
   System.out.println(
     "Changing the salary of employee of company 2 to 60,000"
   );
   company2.Employee.salary = 60000;

   System.out.println(
     "Salary of Employee of company2: " + company2.Employee.salary + "\n\n"
   );

   //This change will be reflected in original 'company1'
   System.out.println("Updated Details of Company 1:");
   System.out.println(
     "Name of employee of Company 1: " + company1.Employee.name
   );
   System.out.println(
     "Salary of employee of Company 1: " + company1.Employee.salary
   );
 }
}

Output:

Details of Company 1: 

Id: 0
Name: CodingNinjas
Course Id: Rahul


Details of Company 2: 

Id: 1
Name: CodingNinjas
Course Id: Rahul

Changing the salary of employee of company 2 to 60,000
Salary of Employee of company2: 60000

Updated Details of Company 1:
Name of employee of Company 1: Rahul
Salary of employee of Company 1: 50000

Also see, Duck Number in Java

FAQs

1. What is cloning in Java?
Ans: Object cloning is a way to create an exact copy of an object. The 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.

 

2. Is a Java clone a deep copy?
Ans: clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable, you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.

 

3. What happens when a class does not implement a Cloneable class and tries to clone its objects?
Ans: The CloneNotSupportedException would be thrown.

 

4. Why do we override the clone method?
Ans: We override the clone method() of the object class and declare it protected so that it is accessible only to the subclasses of the current class.

Key Takeaways

In this blog, we understood the topic of object cloning in great detail. We extensively explored the concepts of cloning in Java by going through both types of cloning namely shallow and deep cloning. We also discussed the problem with the assignment operator and discussed the Cloneable interface as well. We saw the concepts taught in this blog in action with the help of examples.
We hope that this blog has helped you enhance your knowledge regarding testing using Mocha. If you would like to learn more, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Java Annotations
Next article
Lambda Expressions in Java
Live masterclass