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:
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());  
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With