Consider the code below:
DummyBean dum = new DummyBean();
dum.setDummy(\"foo\");
System.out.println(dum.getDummy()); // prints \'foo\'
DummyBean dumtwo = du
class DB {
private String dummy;
public DB(DB one) {
this.dummy = one.dummy;
}
}
You can try to implement Cloneable
and use the clone()
method; however, if you use the clone method you should - by standard - ALWAYS override Object
's public Object clone()
method.
Yes. You need to Deep Copy your object.
To do that you have to clone the object in some way. Although Java has a cloning mechanism, don't use it if you don't have to. Create a copy method that does the copy work for you, and then do:
dumtwo = dum.copy();
Here is some more advice on different techniques for accomplishing a copy.
Deep Cloning is your answer, which requires implementing the Cloneable
interface and overriding the clone()
method.
public class DummyBean implements Cloneable {
private String dummy;
public void setDummy(String dummy) {
this.dummy = dummy;
}
public String getDummy() {
return dummy;
}
@Override
public Object clone() throws CloneNotSupportedException {
DummyBean cloned = (DummyBean)super.clone();
cloned.setDummy(cloned.getDummy());
// the above is applicable in case of primitive member types like String
// however, in case of non primitive types
// cloned.setNonPrimitiveType(cloned.getNonPrimitiveType().clone());
return cloned;
}
}
You will call it like this
DummyBean dumtwo = dum.clone();