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

后端 未结 6 1736
轻奢々
轻奢々 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:50

    In Java, it's generally correct to think of any variable which is an Object as being a pointer to a value of that Object type. Therefore, the following in Java:

    Color a = new Color(), b = new Color();
    
    a.setColor(blue);
    b.setColor(red);
    a = b;
    b.setColor(purple);
    b = a;
    

    Should do more or less the same thing as the following in C++:

    Color *a = new Color();
    Color *b = new Color();
    
    a->setColor(blue); // the value a points to is now blue
    b->setColor(red); // the value b points to is now red
    a = b; // a now points to the same value as b.
    b->setColor(purple); // the value BOTH a and b point to is now purple
    b = a; // this does nothing since a == b is already true
    

    (Note that this is NOT the same as references - as per this article).

    Also note that, for primitives, Java variables are simply values - NOT pointers. So, in the case of primitive integers, it should behave more or less as you expect in your question, since a = b is setting the value of a equal to the value of b.

提交回复
热议问题