Shallow Copy in Java

Posted by Vilius on Stack Overflow See other posts from Stack Overflow or by Vilius
Published on 2010-04-25T18:05:06Z Indexed on 2010/04/25 18:13 UTC
Read the original article Hit count: 285

Filed under:
|
|

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 ....

© Stack Overflow or respective owner

Related posts about java

Related posts about copy