This article was reproduced from: http://blog.csdn.net/mengxiangyue/article/details/6818611
We may have encountered this in Java, and when we pass an object as a parameter to a function, what we want to do in this function does not affect the object itself. But in the Java Pass is a reference, so often we change the object within the function of a certain value, when the object is called outside the function, the corresponding value is also changed, such as the following program:
Class Test
{
static void MyMethod (Point pt1)
{
pt1.x = 23;
System.out.println ("x=" +pt1.x);
}
public static void Main (string[] args)
{
Point pt = new Point (2,4);
System.out.println ("x=" +pt.x);
MyMethod (PT);
System.out.println ("x=" +pt.x);
}
}
Class point{
int x, y;
Point (int x,int y)
{
this.x = x;
This.y = y;
}
}
The result of the output is
x=2
X=23
X=23
But the result we want is that the value of X will not change after we call the function MyMethod () method, which is still 2. Because the arguments in Java are reference types, the result is that we want to pass in a copy of the object, so here we use the Clone () method of the objects.
The cloning implementation takes a few steps:
Overrides the base class's Clone () method in a derived class and declares it to be public.
In the Clone () method of the derived class, call Super.clone ().
Implement the Cloneable interface in a derived class. The Cloneable interface does not have any abstract methods, such that it becomes an identity interface. Implement this interface just to tell the compiler that this object can be cloned. We follow the above steps to modify the above code as follows:
Class Test
{
static void MyMethod (Point pt1)
{
pt1.x = 23;
System.out.println ("x=" +pt1.x);
}
public static void Main (string[] args)
{
Point pt = new Point (2,4);
System.out.println ("x=" +pt.x);
Point pt2 = (point) pt.clone ();
MyMethod (PT2);
System.out.println ("x=" +pt.x);
}
}
Class Point implements cloneable{
int x, y
Point (int x,int y)
{
this.x = x;
this.y = y;
}
public Object clone ()
{
point p = null;
try
{
p = (point) super.clone ();
}
catch (Exception e)
{
e.printstacktrace ();
}
return p;
}
The result of the output is:
x=2
X=23
x=2
First we override the Clone () method of the object class in the derived class and declare it as public. Then we call the Super.clone () method, which throws an exception (for this exception you can view the Java Help document yourself), so you must use Try......catch ... The statement captures, and then returns this object. Here you need to explain that the Clone () method returns an object type, so you need to force the type conversion
For the Javaclone () method of the analysis of hope to bring you help.
A brief analysis of the Clone () method in Java