clone() method in java

cloning :- we are get clone object by using clone() method of object class. the process of creating exactly duplicate object is called cloning. for maintain backup copy we are using clone method.

When we are using clone() method we are consider following things.

  • If we are using clone() method compulsory there should be handle CloneNotSupportedException  either by try, catch or by throws keyword, otherwise we get compile time error.
  • We should be perform type casting because return value of clone() method is object.
  • We will be call clone() method only on cloneable object.
  • It is a marker interface.

      Syntax :-  protected Object clone() throws CloneNotSupportedException

There are two type of cloning.

Shallow cloning :-

The process of creating exact duplicate reference variable is called shallow cloning.

				
					public class ShallwoCloningTest implements Cloneable {

	int i = 30;
	int j = 40;

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

	public static void main(String[] args) throws CloneNotSupportedException {

		ShallwoCloningTest d1 = new ShallwoCloningTest();
		ShallwoCloningTest d2 = (ShallwoCloningTest) d1.clone();

		System.out.println(d1.i + "----- " + d1.j);
		System.out.println("After shallow cloning ");
		System.out.println(d2.i + "----- " + d2.j);
	}
}
				
			

Output :-
30—– 40
After shallow cloning
30—– 40

Deep cloning :-

The process of create exact duplicate object is called deep cloning.

				
					public class DeepCloningTest implements Cloneable {

	int i = 10;
	int j = 20;

	public Object clone() throws CloneNotSupportedException {
		Object obj = super.clone();
		DeepCloningTest d = (DeepCloningTest) obj;
		return d;
	}

	public static void main(String[] args) throws CloneNotSupportedException {

		DeepCloningTest d1 = new DeepCloningTest();
		DeepCloningTest d2 = (DeepCloningTest) d1.clone();

		System.out.println(d1.i + "----- " + d1.j);
		System.out.println("After deep cloning ");
		System.out.println(d2.i + "----- " + d2.j);
	}
}
				
			

Output :-
10—– 20
After deep cloning
10—– 20