clone
package one.test; public 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(); System.out.println("x=" + pt2.x + " y=" + pt2.y); 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; }
@Override public Object clone() {
Point p = null; try {
//这里并没有对xy赋值,但是却把值拷贝过去了,难道是继承Cloneable的结果?
p = (Point) super.clone(); } catch (Exception e) { e.printStackTrace(); } return p; } }
x=2
111111
x=2 y=4
x=23
x=2

浙公网安备 33010602011771号