0

I am trying to build a method to deep copy a class:

public MyClass clne() {
    MyClass cpy = new MyClass();
    cpy.var1 = getVar1(); //getVar1 is a method returning the value of var1
    cpy.var2 = getVar2();
    return cpy;
}

However, when I run:

MyClass x = new MyClass();
x.var1 = 18;
MyClass y = x.clne();
y.myMethod(); // Where myMethod is a method changing the value of var1 to, say 4.
System.out.println(x.var1);

The value of x.var1 is 4.

Am I doing something wrong? Thank you :)

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
Dario
  • 995
  • 1
  • 9
  • 12

1 Answers1

0

You should be creating a new instance of var1 rather than pointing to the old reference, unless they are primitives of course.

cpy.var1 = new Var1( getVar1() );

this will require you to write a copy constructor for whatever class Var1 is. This can be done in other ways though.

Hope that helps.

PS, you are basically doing a shallow copy.

Adrian
  • 495
  • 2
  • 10
  • The OP says that they are primitives, not objects – Patashu Mar 22 '13 at 00:04
  • Is it new Var1 or new var1? (If it makes a difference) – Dario Mar 22 '13 at 00:04
  • Depends on the type of var1. as you assign it using x.var1 = 4, i assume it must either be an int or Integer, which means that what you wrote should be fine unless they are static members – Adrian Mar 22 '13 at 00:28