I have this code in Java.
public class CloneTest implements Cloneable{
String name;
int marks;
public CloneTest(String s, int i) {
name = s;
marks = i;
}
public void setName(String s) {
name = s;
}
public void setMarks(int i) {
marks = i;
}
@Override
public Object clone() {
return new CloneTest(this.name, this.marks);
}
}
I have created one object of this class, and then cloned it. Now, when I change the value of name
in one object, the value of name remains unchanged in the other. The strange thing here is in the constructor, I am just using a simple reference for name
, not creating a new String
for name
. Now, since String
s are reference types, I expected the String
in the clone to be changed as well. Can anyone tell me what's going on? Thanks in advance!
EDIT
Code Testing
CloneTest real = new CloneTest("Molly", 22);
CloneTest clone = real.clone();
real.setName("Dolly");
I used the "Inspect Variables" feature of BlueJ to check the values.