0

I would post my program (roulette), but it's created in my language, and there would be alot. So this is exactly as the classes in my program work. I didn't know how to google this issue correctly.

Class Class1{
     int variable1=0;
}
Class Class2{
     Class1 variableC1;
     Class1 variableC2;
}
void main(){
     Class2 someClass2 = new Class2();
     Class1 someClass1 = new Class1();

     someClass2.variableC1=someClass1;
     someClass2.variableC2=someClass1;//that's the way I have to set them in my program, or else it doesn't work

     someClass2.variableC1.variable1=1001; //now this will set both the variableC1 and variableC2 to 1001, even tho i want variableC2.variable1 to stay at 0

}

So as I said in the comments, when i set one class' variable, both change even tho i only want the one to.
I know this looks like horible programing, I think the same, but that's the only way it worked for me (and the only way i know how to, new to objects). Any suggestions would be great.

Nino Klajnsek
  • 29
  • 1
  • 5
  • In Java, an object is *not* implicitly copied/cloned/duplicated when it is assigned to a variable or used as a method parameter. Thus, changing *that* object anywhere changes *that* object everywhere; the name/expression used to evaluate to the object modified is irrelevant. – user2864740 Dec 18 '15 at 21:49
  • This question (and observed behavior) works the exact same way as when an object is passed to a method and then modified. – user2864740 Dec 18 '15 at 21:50

4 Answers4

2

in Java, object variables are defined by reference. this means that when you do:

someClass2.variableC1=someClass1;

what you actually do is setting variableC1 to point to the location in memory in which someClass1 is stored, and the same for variableC2.

So since both variables point to the same location in memory, once you change the object in this location, both pointers to it are effected.

Nir Levy
  • 12,750
  • 3
  • 21
  • 38
0

You have to remember that unless you're working with primitives in java, everything is a reference. So when you set variableC1 and variableC2 to both be someClass1, they're now both pointing to the same object. A change to one will be reflected in the other.

Slepz
  • 460
  • 3
  • 18
0

A class in the stack is really a reference to memory in the heap. In Java a class is very similar to a pointer in C/C++.

So, when you set variableC1 and variableC2 both to someClass1 they both become references to the same memory in the heap. When you change that memory in the heap, because they both reference that same memory, both variables have changed.

William Rosenbloom
  • 2,506
  • 1
  • 14
  • 37
0

Try this:

 someClass2.variableC1=new someClass1();
 someClass2.variableC2=new someClass1();

You must create 2 objects with new. Otherwise, both will refer to the same object, that is what is done with the = operator: copy the reference, in the case of objects.

Eduardo Poço
  • 2,819
  • 1
  • 19
  • 27