object a = object b; what happens to object a?

后端 未结 6 1733
轻奢々
轻奢々 2021-01-17 15:22

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         


        
6条回答
  •  -上瘾入骨i
    2021-01-17 15:43

    a and b are references to objects. When you write a=b then a is assigned to the reference that was previously assigned to b, so they now both reference the same object.

    So, let's say you have two objects, O1 and O2, which at the beginning are assigned to a and b respectively.

    a.setColor(blue);     // the object O1 is set the color blue
    b.setColor(red);      // the object O2 is set the color red
    a = b;                // a now references O2, and b still references O2.
    b.setColor(purple);   // the object O2 is set the color purple.
    b = a;                // b is told to reference O2, which it already is.
    

    If you want to think through the mind of C, you can see a and b as pointers, that can be exchanged between variables and whose data can be modified.

    It's not the same for primitive values which are handled like they do in C.

提交回复
热议问题