62,623
社区成员
发帖
与我相关
我的任务
分享
package clone;
public class CloneTest {
public static void main(String[] args) {
Clone c=new Clone();
c.setStr("1");
Clone c1;
try {
c1 = (Clone)c.clone();
System.out.println("深复制 "+c+"\t"+c1);
c1.setStr("2"); //改变了一个对象
System.out.println("深复制 "+c+"\t"+c1);//深复制另一个没改变
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
Check check=new Check();
check.setStr("1");
Check check2=check;
System.out.println("浅复制 "+check2+"\t"+check);
check2.setStr("2"); ////改变了一个对象
System.out.println("浅复制 "+check2+"\t"+check);//深复制另一个改变了
}
}
//深复制对象
class Clone implements Cloneable{
public String str="";
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
protected Object clone() throws CloneNotSupportedException {
Clone c=(Clone)super.clone();
return c;
}
public String toString() {
return this.str;
}
}
//浅复制对象
class Check{
String str="";
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public String toString() {
return this.str;
}
}
class Test {
private final int id;
Test() {
id = 1;
}
Test(int id) {
// this(); // 这样是不行的哦
this.id = id;
}
public static void main(String[] args) {
}
}