I have a class and two instances. I want to make partial copy of objects.
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");
Here is the output.
Printing test1
Name: newName
Subject: newSubject
Printing test2
Name: newName
Subject: newSubject
What I want is test1 to retain its name while letting test2 to modify rest of the members such that whenver test2 modifies any variable, it is reflected in test1 (except name). Is there anyway to achieve this functionality?
Desired output:
Printing test1
Name: myName
Subject: newSubject
Printing test2
Name: newName
Subject: newSubject
You'll need to split it into two classes. test1
and test2
will need to be different objects that contain another object that is shared between them. In the code below I call that shared object 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);
}
}
Test runner
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()
));
}
}
Test output
Printing test1
Name: myName
Subject: newSubject
Printing test2
Name: newName
Subject: newSubject