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?
There is no copy, there are two references to the same instance of
Ball
after this assignment:To create a copy, implement a copy constructor for
Ball
:To use:
You have only one
Ball
object. BothmyBall
andmySecondBall
references pointing to sameBall
object.As others have said, the issue is that you have two references to the same actual instance. An analogy I like to use is that you have two remote controls for the same television.
If you want to have two balls, you might do something like:
The above solution will surely work.
Objects are compound values, hence by equating an object to some variable doesn't create its copy, rather passes its reference. Therefore changing one will affect another. If someone wanna know more ways to solve this, they can try any of the below methods-
OR
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());