Cloning (programming)
From Wikipedia, the free encyclopedia
Cloning refers to the making of an exact copy of an object, frequently under the paradigm of instance-based programming, or object-oriented programming.
[edit] Shallow copies
In all languages, variables such as int, float, double, long, etc. simply store their values somewhere in the computer's memory (arbitrarily by the operating system). by using simple assignment, you can copy the contents of the variable to another one:
//Fig. 1 (Java Code) int original = 42; int copy = null; //Copies contents original to copy (replaces copy's original value) copy = original;
However, when "copying" objects this way, it does not actually "copy" the original. Eg:
//Fig. 2 (Java Code) Object original = new Object(); Object copy = null; //NOT copying Object, but copying its reference copy = original
In object-oriented programming, everything is encapsulated in entities called objects. Objects can contain methods, which can be user defined or inheirited from their superclass. They can also contain variables holding any datatype, including their array types. Objects generally are created by using the popular new keyword:
//Fig. 3 <Java Object) Object myObj = new Object();
This instantiates, or creates, an object and puts it into some piece of memory in the computer, and returns a reference to the instantiated object. So the variable myObj effectively holds a reference rather than the actual object itself. This is why the code in Fig. 2 copies only the reference, and not the actual object. So the variable original and copy actually point to the same thing! The reason why this is done is for efficiency. Instead of copying the entire object to assign it to the destination variable (which the object can get very large), and instead just juggle around references (which are simply integers in C/C++), it makes the distribution of the object around in a program (eg. passing it as an argument to a method), much more efficient.
This process of passing references around is called shallow copying.
[edit] Cloning
The process of actually making another exact replica of the object, instead of just its reference, is called cloning. In most languages, the language or libraries can facilitate some sort of cloning. In Java, the Object class contains the clone() method, which copies the object and returns a reference to that copied object. Since it is in the Object class, all classes defined in Java will have a clone method available to the programmer. In C++, a simple memcpy() operation (part of the Standard Library) will copy the contents of the object into a memory space, thus cloning the object.