Java.lang.Object.clone() Method


The java.lang.Object.clone() creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression −

 x.clone() != x

will be true, and that the expression −

x.clone().getClass() == x.getClass()

will be true, but these are not absolute requirements. While it is typically the case that −


will be true, this is not an absolute requirement.


Following is the declaration for java.lang.Object.clone() method

protected Object clone()



Return Value

This method returns a clone of this instance.


CloneNotSupportedException − if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.


The following example shows the usage of lang.Object.clone() method.

package com.tutorialspoint;

import java.util.GregorianCalendar;

public class ObjectDemo {

   public static void main(String[] args) {

      // create a gregorian calendar, which is an object
      GregorianCalendar cal = new GregorianCalendar();

      // clone object cal into object y
      GregorianCalendar y = (GregorianCalendar) cal.clone();

      // print both cal and y
      System.out.println("" + cal.getTime());
      System.out.println("" + y.getTime());

Let us compile and run the above program, this will produce the following result −

Mon Sep 17 04:51:41 EEST 2012
Mon Sep 17 04:51:41 EEST 2012