What is object cloning in Java?



Object cloning is creating a copy of an object. The clone() method of the Object class of the java.lang package creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.

Example

Live Demo

import java.util.GregorianCalendar; 

public class ObjectDemo {
   public static void main(String[] args) {
      GregorianCalendar cal = new GregorianCalendar();
      GregorianCalendar y = (GregorianCalendar) cal.clone();
      
      System.out.println("" + cal.getTime());
      System.out.println("" + y.getTime());
   }
}

Output

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

I love thought experiments.


Advertisements