Search code examples
javamutable

How are properties of mutable variables shared among multiple variable references?


I'm not sure if this is just me, or if its something I should have known, but if I do :

Object a = 1;
Object b = a;
b = 2;

Then a is the same value as b. Is this normal behaviour? Because I wanted to copy the variable, not reference it.

The reason i ask is i have some code like this :

center = new Point(0.0f,1.0f,1.0f);
returnPoint = center;
...
returnPoint.x = 1.0f;
//For some reason, above modifies center as well as return

Solution

  • You may try something like this:

    center = new Point(0.0f,1.0f,1.0f);
    returnPoint = center.clone();
    ...
    returnPoint.x = 1.0f;
    

    The clone method will create another instance with the same values.