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

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

    Since everybody else has explained the difference between references and primitives I'll explain how this works under the surface.

    So a reference to an object is essentially an number. Depending on the VM it will be either 32 bits or 64 bits, but it's still a number. This number tells you were in memory the object is. These numbers are called addresses and are usually written in hexadecimal base like so 0xYYYYYYYY (this is an example of a 32 bit address, a 64 bit address would be twice as large).

    Let's use your example from above using a 32 bit VM

    a.setColor(blue); // Let's assume the object pointed to by a is at 0x00000001
    b.setColor(red);  // Let's assume the object pointed to by b is at 0x00000010
    
    /* Now the following makes sense, what happens is the value of 
       a (0x00000001) is overwritten with 0x00000010. 
       This is just like you would expect if a and b were ints.
    */
    a = b; // Both a and b have the value 0x00000010. They point to the same object
    
    b.setColor(purple); // This changed the object stored at 0x00000010 
    
    b = a; // This says nothing because both a and b already contain the value 0x00000010
    

    This should illustrate that references do work like numbers as you showed in your second example. However only under the surface, as far as you the programmer is concerned assignment of references don't work like assignment with primitives.

    In Java you will never need to worry about the addresses of objects and the likes. In languages like C and C++ which enable lower level access this becomes more apparent and important.

    Arithmetics? So can you do arithmetics and other stuff you can do with numbers? The shorter answer is no, not in java at least.

    In C and C++ incrementing and decrementing pointers to objects is however perfectly valid and used a lot, for example to traverse arrays.

    Feel free to ask questions if this wasn't clear enough.

提交回复
热议问题