< Back to index

clone() is a system call on the Linux Kernel related to multithreading. clone() is also a method in the Java programming language for object duplication.

Linux C clone function


The syntax for calling clone under a Linux is program is:

#include
int clone (int (*fn) (void *), void *child_stack, int flags, void *arg);

clone creates a new thread that starts with function pointed to by the fn argument (as opposed to fork() which continues with the next command after fork().) The child_stack argument is a pointer to a memory space to be used as the stack for the new thread (which must be malloc'ed before that; on most architectures stack grows down, so the pointer should point at the end of the space), flags specify what gets inherited from the parent process, and arg is the argument passed to the function. It returns the process ID of the child process or -1 on failure.

Java clone method


Because objects in Java are referred to using reference types, there is no direct way to copy the contents of an object into a new object. Assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself.

The Java class contains a clone() method that creates and returns a copy of the object. By default, classes in Java do not support cloning and the default implementation of clone throws a {{Javadoc:SE|java/lang|CloneNotSupportedException}}. Classes wishing to allow cloning must implement the marker interface {{Javadoc:SE|java/lang|Cloneable}}. Since the default implementation of Object.clone only performs a shallow copy, classes must also override clone to provide a custom implementation when a deep copy is desired.

The syntax for calling clone in Java is:

Object copy = obj.clone();

or commonly

MyClass copy = (MyClass) obj.clone();

which provides the typecasting needed to assign the generic Object reference returned from clone to a reference to a MyClass object.

This entry uses material from from Wikipedia, the leading user-contributed encyclopedia. It is licensed under the GNU Free Documentation License. Disclaimer.