Java/J2EE and SOA (346 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (17 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (343 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is Cloning in Java and its Types?

Last updated on Nov 26,2019 14.6K Views

Swatee Chand
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...
12 / 14 Blog from Java OOPS

While programming, often we come across scenarios where we need to reuse a complete piece of code. Rewriting the code makes the program bulky, all while decreasing the efficiency of the program. Thus, Java provides us with an excellent feature which rescues is from this burdensome task. This is known as Cloning in Java and through the medium of this article, I will give you complete insights into it.

Below are the topics I will be discussing in this article:

Cloning in Java

Object cloning in Java is the process of creating an exact copy of the original object. In other words, it is a way of creating a new object by copying all the data and attributes from the original object. This is only possible by implementing clone() method of the java.lang.Object class. 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. One thing that you must remember, in Java, the objects which implement the clone interface which is a marker interface is allowed to use the clone().

Now that you are aware of what is cloning in Java let’s see various advantages of using this feature.

Advantages of Cloning in Java

Below I have listed down a few of the most intriguing features of using cloning in Java.

  • Helps in reducing the lines of code.
  • The most effective and efficient way of copying objects.
  • Also, the clone() is considered to be the fastest method to copy an array.

Note: Though using cloning might result in some design issues but if you use it in a proper strategical way it can benefit you.

Types of Cloning in Java

Cloning in Java can be grouped into two categories:

  1. Shallow Cloning
  2. Deep Cloning

Let’s understand each of them one by one.

Shallow Cloning

In Java, when the cloning process is done by invoking the clone() method it is called Shallow Cloning. It is the default cloning process in Java where a shallow copy of the original object will be created with exact field. In case the original object has references to some other objects as fields, then only the references of that object will be cloned instead of new object creation. In other words, if you change the value of the cloned objects then it will be reflected in the original as well. Thus, shallow cloning is dependent on the original object.

shallow copy - Cloning in Java - EdurekaBelow I have given the example of the same:

package edureka;

class EduCourse
{
    String course1; 
    String course2;
    String course3;
 
    public EduCourse(String crs1, String crs2, String crs3)
    {
        this.course1 = crs1;
 
        this.course2 = crs2;
 
        this.course3 = crs3;
    }
}
 
class EduLearner implements Cloneable
{
    int eduId; 
    String learnerName; 
    EduCourse eduCourse;
 
    public EduLearner(int eduId, String learnerName, EduCourse eduCourse)
    {
        this.eduId = eduId; 
        this.learnerName = learnerName; 
        this.eduCourse = eduCourse;
    }
 
    //Default version of clone() method
 
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}
 
public class ShallowCloneSample
{
    public static void main(String[] args)
    {
        EduCourse j2ee = new EduCourse("Java", "Spring", "Microservices");
 
        EduLearner learner1 = new EduLearner(2811, "Max", j2ee);
 
        EduLearner learner2 = null;
 
        try
        {
            //Creating a clone of learner1 and assigning it to learner2
 
        	learner2 = (EduLearner) learner1.clone();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
        
        //Printing Details of Learner1
        System.out.println("Details of Learner 2: ");
        System.out.println("Id: "+learner1.eduId);
        System.out.println("Name: "+learner1.learnerName);
        System.out.println("Course Id: "+learner1.eduCourse);
        
        //Printing all the courses of 'learner1'
        System.out.println("Courses of Learner 1: ");
        System.out.println(learner1.eduCourse.course1);
        System.out.println(learner1.eduCourse.course2);
        System.out.println(learner1.eduCourse.course3);
        
      //Printing Details of Learner2
        System.out.println("Details of Learner 2: ");
        System.out.println("Id: "+learner2.eduId);
        System.out.println("Name: "+learner2.learnerName);
        System.out.println("Course Id: "+learner2.eduCourse);
        
        
      //Printing all the courses of 'learner2'
        System.out.println("Courses of Learner 2: ");
        System.out.println(learner2.eduCourse.course1);
        System.out.println(learner2.eduCourse.course2);
        System.out.println(learner2.eduCourse.course3);       
 
        //Changing the course3 of 'learner2' 
        learner2.eduCourse.course3 = "JSP";
 
        //This change will be reflected in original 'learner1' 
        System.out.println("Updated Courses of Learner 2:");
        System.out.println(learner1.eduCourse.course1);
        System.out.println(learner1.eduCourse.course2);
        System.out.println(learner1.eduCourse.course3);
    }
}

Output:

Details of Learner 2: 
Id: 2811
Name: Max
Course Id: EduCourse@15db9742
Courses of Learner 1: 
Java
Spring
Microservices
Details of Learner 2: 
Id: 2811
Name: Max
Course Id: EduCourse@15db9742
Courses of Learner 2: 
Java
Spring
Microservices
Updated Courses of Learner 2:
Java
Spring
JSP

Deep Cloning in Java

In Java, when the cloning process is done by implementing the Cloneable interface it is called Deep Cloning. In this type of cloning, an exact copy of all the fields of the original object will be created. But in case, the original object has references to other objects as fields then a copy of those objects will also be created by calling the clone() method. This makes the cloned object independent of the original object and any changes made in any of the object won’t be reflected on the other.

deep copy - Cloning in Java - Edureka

Below I have given the example of the same:

package edureka;
class EduCourse implements Cloneable
{
    String course1;
    String course2;
    String course3;
 
    public EduCourse(String crs1, String crs2, String crs3)
    {
        this.course1 = crs1; 
        this.course2 = crs2; 
        this.course3 = crs3;
    }
 
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}
 
class EduLearner implements Cloneable
{
	int eduId; 
    String learnerName; 
    EduCourse eduCourse;
 
    public EduLearner(int eduId, String learnerName, EduCourse eduCourse)
    {
    	this.eduId = eduId; 
        this.learnerName = learnerName; 
        this.eduCourse = eduCourse;
    }
 
    //Overriding clone() method for creating a deep copy of an object
 
    protected Object clone() throws CloneNotSupportedException
    {
        EduLearner learner = (EduLearner) super.clone();
 
        learner.eduCourse = (EduCourse) eduCourse.clone();
 
        return learner;
    }
}
 
public class DeepCloneSample
{
    public static void main(String[] args)
    {
        EduCourse j2ee = new EduCourse("Java", "Spring", "Microservices"); 
        EduLearner learner1 = new EduLearner(2811, "Max", j2ee); 
        EduLearner learner2 = null;
 
        try
        {
            //Creating a clone of learner1 and assigning it to learner2
 
            learner2 = (EduLearner) learner1.clone();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
 
      //Printing Details of Learner1
        System.out.println("Details of Learner 2: ");
        System.out.println("Id: "+learner1.eduId);
        System.out.println("Name: "+learner1.learnerName);
        System.out.println("Course Id: "+learner1.eduCourse);
        
        //Printing all the courses of 'learner1'
        System.out.println("Courses of Learner 1: ");
        System.out.println(learner1.eduCourse.course1);
        System.out.println(learner1.eduCourse.course2);
        System.out.println(learner1.eduCourse.course3);
        
      //Printing Details of Learner2
        System.out.println("Details of Learner 2: ");
        System.out.println("Id: "+learner2.eduId);
        System.out.println("Name: "+learner2.learnerName);
        System.out.println("Course Id: "+learner2.eduCourse);
        
        
      //Printing all the courses of 'learner2'
        System.out.println("Courses of Learner 2: ");
        System.out.println(learner2.eduCourse.course1);
        System.out.println(learner2.eduCourse.course2);
        System.out.println(learner2.eduCourse.course3);       
 
        //Changing the course3 of 'learner2' 
        learner2.eduCourse.course3 = "JSP";
 
        //This change won't be reflected in original 'learner1' 
        System.out.println("Courses of Learner 1:");
        System.out.println(learner1.eduCourse.course1);
        System.out.println(learner1.eduCourse.course2);
        System.out.println(learner1.eduCourse.course3);
        
        //Updated Courses of learner2
        System.out.println("Courses of Learner 2:");
        System.out.println(learner2.eduCourse.course1);
        System.out.println(learner2.eduCourse.course2);
        System.out.println(learner2.eduCourse.course3);
    }
}

Output:

Details of Learner 2: 
Id: 2811
Name: Max
Course Id: edureka.EduCourse@15db9742
Courses of Learner 1: 
Java
Spring
Microservices
Details of Learner 2: 
Id: 2811
Name: Max
Course Id: edureka.EduCourse@6d06d69c
Courses of Learner 2: 
Java
Spring
Microservices
Courses of Learner 1:
Java
Spring
Microservices
Courses of Learner 2:
Java
Spring
JSP

This brings us to the end of this article on Cloning in Java. If you want to know more about Java you can refer to our other Java Blogs.

Now that you have understood what is a Cloning in Java, check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Cloning in Java” article and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDate
Java Certification Training Course

Class Starts on 28th January,2023

28th January

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th February,2023

25th February

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is Cloning in Java and its Types?

edureka.co