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?
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 Ballcopying the same color:Ball mySecondBall = new Ball(myBall.getColor());