What Is an Object Copy?

In object-oriented computer programming, an object copy is the procedure used to create an exact duplicate of an existing data object. The new data object is usually completely independent of the original object, except that they share the same class definition. Object-oriented programming attempts to encapsulate both the data and the methods that operate on the data into a single object, so it can be difficult to perform an object copy, especially in an instance in which an object has private or protected fields. The bulk of the mechanics of an object copy are left to the programmer, because most objects are user created; however, some mechanisms — such as the clone method in Java — provide a loose framework for the process.

Depending on the language being used for programming, there might be two separate types of an object copy that can be performed. Unlike a true object copy, in which the resulting object is separate from the source object, a shallow copy can create two references to the same data fields in memory. Using operators and pointers, the fields of a new object can be set to the memory locations of the matching data fields in the source object, essentially creating two objects that point to the exact same information. This is not possible in some programming languages, however.

A more traditional method of performing an object copy is to create an instance matching the class of the source object. Through user-defined methods within the class, all of the variable data within the source object can be manually copied to the destination object, creating an exact copy, although the information in the new object is independent of the source object’s data and is stored in different memory locations. This is sometimes known as cloning an object.

Some programming languages, such as Java and C++, provide some guidance when dealing with object-copy procedures. Both languages have standard methods that can be overridden to implement object-copy functionality, although they are more or less empty as implemented by the languages. Through inheritance, however, if the methods are constantly updated in each subclass, then an object can be copied easily with one call to a method.

In network situations, some more cumbersome methods of creating copies of instanced objects have been developed. One of these is to write the object to be copied to a data stream and then receive the stream in a new instance of the class, effectively copying it as if it were being transmitted across a network or read from a file. This method can be used in situations in which access to the object’s fields is restricted and no copy methods or interfaces are defined.