Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clone
method
java

What is the clone method in Java

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

When working with objects in Java, we often need to create copies of them. We can create two different types of copies - shallow copies and deep copies. In this Answer, we will explore how these copies can be created and then learn what the clone() function is and how it can be used for making copies of objects.

Shallow copy

A shallow copy involves creating a copy of an object such that we simply make another reference to the object under consideration instead of creating a new object itself. Because of this, making a change to any of the references causes the change to be consolidated in the object referred to. Thus, this change is reflected in all the references to that object.

The code below demonstrates this.

// A Example class whose objects are cloned
class Example 
{
	int x ;
  	int y ;

	Example()
	{
		x = 0;
		y = 0;
	}
}


class Main 
{
	public static void main(String[] args)
	{
		Example obj1 = new Example();

		System.out.println("The initial values of x and y (when obj1 is first made) are: " + obj1.x + " " + obj1.y);

		Example obj2 = obj1; // shallow copy - obj2 is a reference to the same object referred to by obj1

    System.out.println("The initial values of x and y (when obj2 is first made) are: " + obj2.x + " " + obj2.y);

		obj2.x = 100; // changing obj.x

		System.out.println("\n\nThe values of x and y (of obj1) after obj2.x is changed from to 100 are: " + obj1.x + " " + obj1.y);
		System.out.println("The values of x and y (of obj2) after obj2.x is changed from to 100 are: " + obj2.x + " " + obj2.y);
	}
}
It can be seen that even though obj2.x was changed, obj1.x is also changed (since obj2 was a shallow copy)

The diagram below illustrates how obj1 and obj2 in the code above refer to the same object of the class Example.

widget

Deep copy

A deep copy involves making a copy of an object such that we create a new object altogether. Then, to transfer the content of the original object's members to the members of this new object, we copy them individually. Now, when one of the objects is changed, the change is isolated to that object only (i.e., it isn't reflected in the other object) since there are two separate objects now. The code below demonstrates this.

// A Example class whose objects are cloned
class Example 
{
	int x ;
  	int y ;

	Example()
	{
		x = 0;
		y = 0;
	}
}


class Main 
{
	public static void main(String[] args)
	{
		Example obj1 = new Example();

		System.out.println("The initial values of x and y (when obj1 is first made) are: " + obj1.x + " " + obj1.y);

		// deep copy
        Example obj2 = new Example(); 

        // copying the members of obj1 into obj2 individually
        obj2.x = obj1.x ;
        obj2.y = obj2.y ;


        System.out.println("The initial values of x and y (when obj2 is first made) are: " + obj2.x + " " + obj2.y);

		obj2.x = 100; // changing obj2.x

		System.out.println("\n\nThe values of x and y (of obj1) after obj2.x is changed from to 100 are: " + obj1.x + " " + obj1.y);
		System.out.println("The values of x and y (of obj2) after obj2.x is changed from to 100 are: " + obj2.x + " " + obj2.y);
	}
}
It can be seen that only obj2.x has been changed here (obj1.x wasn't affected since obj2 was a deep copy)

The diagram below illustrates how obj1 and obj2 in the code above refer to separate objects of the class Example.

widget

Now, we can note that if our class had a lot of members, we would have to copy each of them individually, which would add unnecessary code to our program. To do this more efficiently, we can use the clone() method.

Deep using the clone() method

The clone() method can be used to create a deep copy of an object such that we don't have to copy all the members individually. However, there are a few things we need to take note of syntactically.

  • All Java classes extend the Object class by default. In this super-class, there is a clone() method that has the protected access specifier (meaning that the child class can't access it). Thus, in our class, we need to override this clone() method.
  • This clone() function in the Object super-class throws an exception CloneNotSupporedException. Thus, this over-ridden function in our class (and any other class/function we call this method) must do the same.
  • By default, classes in Java can't be cloned (for security reasons). If we want objects of our class to be cloneable, we must explicitly state this with our class definition. This is done by writing implements Cloneable after the class name (when defining it).

The code below shows how the clone() method is used, and how it works.

// A Example class whose objects are cloned
class Example implements Cloneable
{
	int x ;
  	int y ;

	Example()
	{
		x = 0;
		y = 0;
	}

  @Override
  public Object clone() throws CloneNotSupportedException
  {
    return super.clone() ;
  }
}


class Main 
{
	public static void main(String[] args) throws CloneNotSupportedException
	{
		Example obj1 = new Example();

		System.out.println("The initial values of x and y (when obj1 is first made) are: " + obj1.x + " " + obj1.y);

		// deep copy
        Example obj2 = (Example)obj1.clone();

        // copying the members of obj1 into obj2 individually
        obj2.x = obj1.x ;
        obj2.y = obj2.y ;


        System.out.println("The initial values of x and y (when obj2 is first made) are: " + obj2.x + " " + obj2.y);

		obj2.x = 100; // changing obj2.x

		System.out.println("\n\nThe values of x and y (of obj1) after obj2.x is changed from to 100 are: " + obj1.x + " " + obj1.y);
		System.out.println("The values of x and y (of obj2) after obj2.x is changed from to 100 are: " + obj2.x + " " + obj2.y);
	}
}
It can be seen that only obj2.x has been changed here (obj1.x wasn't affected since obj2 was a deep copy)

NOTE: To learn more about the difference between shallow and deep copies in Java, refer to this link.

Object cloning is a way to create an exact copy of an object. The clone() method of an object class is used to clone an object.

Cloning can also be done using an assignment operator (e.g., object2 = object1) but this will never create a new object. An assignment operator will help object2 point to the location of object1, but any changes in object2 will be reflected in object1. This issue is solved by the clone() method that creates a new object and lets the two objects remain independent.

The following slides will help you understand the key difference between the assignment operator and the clone method:

1 of 7

Advantages of using the clone() method

  • It allows two objects to exist independently, despite being copies of one another.

  • Cloning is the fastest way to copy objects.

  • If we use a copy constructor, then we have to copy all of the data over explicitly, however, cloning copies data automatically.​

Code

The following example shows the cloning of an object:

class objects implements Cloneable 
{ 
    int num; 
    public Object clone() throws
                   CloneNotSupportedException 
    { 
        return super.clone(); 
    } 
} 
  
// Driver class 
class Main 
{ 
    public static void main(String args[]) throws
                          CloneNotSupportedException 
    { 
        objects object1=new objects();//creating object1
        object1.num=5;//setting object1's num = 5
        objects object2=new objects();//creating object2
        
        //display object1's num      
        System.out.println("Initially Object1's num is : " + object1.num);

        //Creating a cloned object
        objects clonedObject=(objects)object1.clone();
        clonedObject.num=10;//changing cloned object's num
        System.out.println("After cloning Object1's num is : " + object1.num);

        object2=object1; //using assignment operator
        object2.num=10; //changing object2's num
        
        //display object1's num 
        System.out.println("After assignment operator Object1's num is : " + object1.num);

    }
} 

RELATED TAGS

clone
method
java
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring