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

后端 未结 6 1735
轻奢々
轻奢々 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条回答
  •  生来不讨喜
    2021-01-17 15:38

    It's because the fact that in first example, a and b are objects so this is what happens in each of the steps:

    a <-- is an object

    b <-- is an object

    a.setColor(blue); <-- a becomes blue

    b.setColor(red); <-- b becomes red

    a = b; <-- IMPORTANT:: original a object is released and available for garbage collection and now a holds the reference of b object, which mean a and b are referring the same object now, which is b.

    b.setColor(purple); <-- b is purple now. Since a points to b only, a is also purple

    Answer: Both a and b are purple at this point.

提交回复
热议问题