sneppets-java8

How to clone or copy the class objects in Java ?

This tutorial guides you on how to clone or copy the class objects in Java. The process of creating an exact copy of an existing class object is called cloning. In cloning, when you clone an object, a bit wise copy of the object will result. Let’s discuss in detail with examples.

Clone or Copy the Class Objects

If you clone an object, the original object and the cloned object will be same exactly bit by bit. Also note that the data present in the original object will also be automatically copied into cloned object. There are two types of cloning. They are shallow cloning and deep cloning.

When you clone the original object and later modify the cloned object, the same modification will affect the original object. This is called as shallow cloning.

And when the cloned object is modified and if this modification does not affect the original object, then it is called as deep cloning.

When we have new operator to create objects why do we need cloning ?

Using cloning mechanism has advantages over using new operator while creating objects. When you create object using new operator, it requires lots of processing done on the original object. And the same processing is required if you wanted to create another object (similar).

But in case of cloning, we get exact copy of the object and it preserves the copy of an intermediate object and hence the original object and cloned object will be processed separately. In this method we can avoid lot of processing that need to be done on the object.

Steps to clone the class objects

Following are the steps to clone object of the class. The clone() method of the Object class is used for cloning.

Step 1: The class whose objects need to be cloned should implement Cloneable interface.

class Person implements Cloneable{

}

Step 2: Write your own method for cloning and call clone() method of Object class.

//our own method for cloning
public Object clonePerson() throws CloneNotSupportedException{
		
    //create cloned object and return
    return super.clone();
}

(OR)

Override the clone() method of Object class to create cloned object with protected identifier.

protected Object clone() {

    return super.clone()
}

Program to clone class objects by writing own method

The following program is an example to clone Person class object by writing our own method.

package com.sneppets.cloning;

class Person implements Cloneable{
	
	int age;
	String name;
	
	public Person (int age, String name) {
		
		this.age = age;
		this.name = name;
	}
	
	public void printData() {
		
		System.out.println("Name= " + this.name);
		System.out.println("Age= " + this.age);
	}
	
        //our own method for cloning
	public Object clonePerson() throws CloneNotSupportedException{
		
                //create cloned object and return
		return super.clone();
	}

}

public class CloneDemo{
	
	public static void main (String[] args) throws CloneNotSupportedException {
		
                //create Person class object using new operator
		Person p1 = new Person(20, "John");
		System.out.println("Original Object");
		p1.printData();
		
                //Cloning - clonePerson() our own method returns object of Object class type
		Person p2 = (Person) p1.clonePerson();
		System.out.println("Cloned Object");
		p2.printData();
	}
}

Ouput

Original Object
Name= John
Age= 20

Cloned Object
Name= John
Age= 20

Clone class objects by overriding Object’s clone() method

Note, it is also possible to create cloned object by overriding clone() method of Object class. You can override clone() method of Object class since it is defined as protected Object clone(). Therefore, you can rewrite the above program by overriding Object’s clone() method.

package com.sneppets.cloning;

class Person implements Cloneable{
	
	int age;
	String name;
	
	public Person(int age, String name) {
		
		this.age = age;
		this.name = name;
	}
	
	public void printData() {
		
		System.out.println("Name= " + this.name);
		System.out.println("Age= " + this.age);
	}
	
    //Overriding clone() method of Object class
	protected Object clone() throws CloneNotSupportedException {
		
		return super.clone();
	}
}

public class CloneDemo{
	
	public static void main (String[] args) throws CloneNotSupportedException {
		
		Person p1 = new Person(20, "John");
		System.out.println("Original Object");
		p1.printData();
		
		//And call overriden clone() method in main
		Person p2 = (Person) p1.clone();
		System.out.println("Cloned Object");
		p2.printData();
	}
}

Ouput

Original Object
Name= John
Age= 20

Cloned Object
Name= John
Age= 20

Do you Know ?

Cloneable interface will not have any members i.e., it will not have any methods and variables and it is called as “Marker Interface”. This interface is used to mark or indicate the class objects are cloneable. Therefore, if we do not implement Cloneable interface then the class objects are not cloneable and clone() method throws “CloneNotSupportedException ” error.

So if any one asks you “Can you write an interface without any methods ?” The answer is yes. An interface without any members is called as “Marker Interface”. Examples are java.lang.Cloneable, java.io.Serializable.

Also See:

References:

guest
0 Comments
Inline Feedbacks
View all comments