对象a =对象b;对象a发生了什么? [英] object a = object b; what happens to object a?

查看:110
本文介绍了对象a =对象b;对象a发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位教授为我们提供了一些考试的练习题,其中一个问题如下(伪代码):

One of my professor has given us a few practice questions for an exam, and one of the questions is something like the below (psuedocode):

a.setColor(blue);
b.setColor(red);
a = b;
b.setColor(purple);
b = a;
//what color is a, and what color is b?

对我来说,这似乎非常初级,因此我提出了答案a是红色",b是红色",但是我被告知这是不正确的.我已经将数学问题分解为答案:

It seems extremely rudimentary to me, so I've proposed the answer that a is 'red', and b is 'red', but I've been told this is incorrect. I've broken down my answer as I would a math problem:

a = 15;
b = 12;
a = b; //a becomes 12
b = 13;
b = a; //b becomes 12

但是我的思考过程是通过C而不是Java进行的.我认为两者都有某种通用方法,但也许我错了?我的答案是错误的还是教授是错误的?我对Java还是很陌生,尽管我有一些C,Python和Web逻辑命令(PHP,Ruby),所以我对此表示歉意.

But my thought process is through the mind of C, not Java. I figured there was some universal method for both, but perhaps I am wrong? Is my answer wrong or my professor is wrong? I'm very new to Java, although I have some command of C, Python, and web logic (PHP, Ruby), so I apologize if this is something trivial (which it is).

推荐答案

假设您已经创建了两个对象,并且使变量ab引用了它们,那么最初您会得到类似的内容. /p>

Assuming you've already created two objects, and made variables a and b refer to them, you've initially got something like this.

a -->  [ white ]     b --> [ white ]

您的前两行会更改对象的颜色,为您提供

Your first two lines change the colours of the objects, to give you

a -->  [ blue  ]     b --> [  red  ]

然后,将变量a指向b引用的对象,以便它们都引用同一对象.您现在拥有

Then, you point the variable a to the object referred to by b, so that they both refer to the same object. You now have

       [ blue  ]     b --> [  red  ] <-- a

然后更改b所引用对象的颜色.

Then you change the colour of the object referred to by b.

       [ blue  ]     b --> [ purple ] <-- a

最后,行b=a;不执行任何操作,因为b已经引用了与a相同的对象.

Lastly, the line b=a; does nothing, because b already refers to the same object as a.

这篇关于对象a =对象b;对象a发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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