我用的是jre 1.6 运行的
package Pack;
public class test implements Cloneable {
private String name;
private int age;
test(String name, int age) {
this.name = name;
this.age = age;
}
public Object clone() {
test o = null;
try {
// Object中的clone()识别出你要复制的是哪一个对象。
o = (test) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
return o;
}
public static void main(String[] args) {
test s1 = new test("zhangsan", 18);
test s2 = (test) s1.clone();
s2.name = "lisi";
s2.age = 20;
//修改学生2后,不影响学生1的值。
System.out.println("name=" + s1.name.hashCode()+ "," + "age=" + s1.age);
System.out.println("name=" + s2.name.hashCode() + "," + "age=" + s2.age);
}
}
结果是:
name=-1432604556,age=18
name=3322003,age=20