Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing one variable changes another

Tags:

java

object

When I create an instance of a ball, and then make a copy of it to another variable, changing the original changes the copy of the ball as well. For example, take the very simplified example below:

class Ball() {
    Color _color;
    public Ball(Color startColor) {
        _color = startColor;
    }
    public void setColor(Color newColor) {
        _color = newColor;
    }
}
Ball myBall = new Ball(black);
Ball mySecondBall = myBall;
myBall.setColor(white);

I've elided an accessor method for _color, but if I get the color of the balls, both of them are now white! So my questions are:

  • Why does changing one object change a copy of it, and
  • Is there a way to copy an object so that you can change them independently?
like image 305
Rob Volgman Avatar asked Oct 28 '25 04:10

Rob Volgman


2 Answers

Ball mySecondBall = myBall;

This does not create a copy. You assign a reference. Both variable now refer to the same object that is why changes are visible to both variables.
You should be doing something like to create a new Ball copying the same color:

Ball mySecondBall = new Ball(myBall.getColor());

like image 73
Cratylus Avatar answered Oct 30 '25 17:10

Cratylus


There is no copy, there are two references to the same instance of Ball after this assignment:

Ball mySecondBall = myBall;

To create a copy, implement a copy constructor for Ball:

class Ball() {
    Color _color;
    public Ball(Color startColor) {
        _color = startColor;
    }
    public Ball(final Ball otherBall) {
        _color = otherBall._color;
    }
    public void setColor(Color newColor) {
        _color = newColor;
    }
}

To use:

Ball myBall = new Ball(black);
Ball mySecondBall = new Ball(myBall);
like image 43
hmjd Avatar answered Oct 30 '25 19:10

hmjd