| Share this post! | Vote this! |
|
Objects in Java are referred using reference types, and there is no
direct way to copy the contents of an object into a new object.
The 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. Here are the details you need to know about cloning Java objects.
For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this: more...
The 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. Here are the details you need to know about cloning Java objects.
Why create a local copy?
The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don't want to modify the method caller's object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this: more...



0 comments:
Post a Comment