Ravi said:
I have java api docs, but still I am not able to understand the use of
clone() method provided by the Object class.
Can You please explain.
The purpose of the clone method is to create an identical copy of
an object.
An identical copy means an instance of the same class with the same
values for all fields. Reference fields will point to the same objects,
primitive type fields will have the same value.
This copy is created without calling any constructors or other
initialization code on the object. This is somewhat acceptable, since
it cannot create an object in an uninitialized state (like the "new"
operator does before the constructors are executed).
If there are further requirements on instances of a class that are
not satisfied if you create an identical copy, then you should not
allow cloning.
Cloning is only allowed for classes that implement the marker
interface java.lang.Clonable, and which expose the clone() method
(which is protected on Object).
The typical way to use cloning is to create a class:
public class MyClass implements Clonable {
// my fields and methods ...
// make a public clone()
public Object clone() {
return super.clone();
}
}
If you need to change the behavior of the clone method, you can
change the cloned copy in your own clone method, e.g., cloning
some referenced objects too instead of referencing the same objects.
/L