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

后端 未结 6 1739
轻奢々
轻奢々 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
    慢半拍i (楼主)
    2021-01-17 15:34

    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  ]
    

    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
    

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

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

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

提交回复
热议问题