更改一个变量会更改另一个变量 [英] Changing one variable changes another

查看:64
本文介绍了更改一个变量会更改另一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建一个球的实例,然后将其副本复制到另一个变量时,更改原始副本也会更改该球的副本.例如,以下面非常简单的示例为例:

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);

我已经省略了_color的访问器方法,但是如果我得到了球的颜色,那么它们现在都是白色的!所以我的问题是:

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:

  • 为什么更改一个对象会更改其副本,并且
  • 是否有一种复制对象的方法,以便您可以独立更改它们?

推荐答案

球mySecondBall = myBall;

这不会创建副本.您分配一个参考.现在,两个变量都指向同一个对象,这就是为什么对两个变量都可见更改的原因.您应该做类似创建 new Ball 并复制相同颜色的操作:

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());

这篇关于更改一个变量会更改另一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆