Shallow Copy in Java
- by Vilius
Hello there!
I already know, what a shallow copy is, but I'm not able to impliment it. Here's a short example.
public class Shallow {
String name;
int number;
public Shallow (String name, int number) {
this.name = name;
this.number = number;
}
}
Test the implementation ...
public class ShallowTest {
public static void main (String[] args) {
Shallow shallow = new Shallow("Shallow", 123);
Shallow shallowClone = new Shallow(shallow);
shallowClone.name = 'Peter';
shallowClone.number = 321;
System.out.println(shallow.name + " - " + shallow.number);
}
}
As I purpose, just the reference of the non primitive datatype String would be copied, so that by calling "shallowClone.name = 'Peter';" I would also change the name of "shallow". Am I right? But somehow, it just does not want to work ....