我有一个班级和两个实例。我想制作一些对象的副本。
public class Testing{
String name;
String subject;
}
Testing test1 = new Testing();
test1.setName("myName");
test1.setSubject("mySubject");
Testing test2 = test1;
test1.setName("newName");
test1.setSubject("newSubject");
这是输出。
Printing test1
Name: newName
Subject: newSubject
Printing test2
Name: newName
Subject: newSubject
我想要的是test1保留其名称,同时让test2修改其余成员,以便当test2修改任何变量时,它会反映在test1中(名称除外)。反正有没有实现这个功能?
期望的输出:
Printing test1
Name: myName
Subject: newSubject
Printing test2
Name: newName
Subject: newSubject
答案 0 :(得分:1)
您需要将其拆分为两个类。 test1
和test2
将需要是包含另一个在它们之间共享的对象的不同对象。在下面的代码中,我称之为共享对象Details
。
<强> Testing
强>
class Testing {
String name;
final Details details;
private Testing(Details details) {
this.details = details;
}
Testing() {
this(new Details());
}
Testing copy() {
return new Testing(details);
}
void setName(String name) {
this.name = name;
}
void setSubject(String subject) {
this.details.subject = subject;
}
String asString() {
return String.format("Name: %s\n%s", name, details.asString());
}
}
<强> Details
强>
class Details {
String subject;
String asString() {
return String.format("Subject: %s", subject);
}
}
测试跑步者
public class Foo {
public static void main(String[] args) throws Exception {
Testing test1 = new Testing();
test1.setName("myName");
test1.setSubject("mySubject");
Testing test2 = test1.copy();
test2.setName("newName");
test2.setSubject("newSubject");
System.out.println(String.format(
"Printing test1\n%s\n\nPrinting test2\n%s",
test1.asString(),
test2.asString()
));
}
}
测试输出
Printing test1
Name: myName
Subject: newSubject
Printing test2
Name: newName
Subject: newSubject