由于其他人都解释了引用和原语之间的区别,我将解释它是如何在表面下工作的。
所以对对象的引用本质上是一个数字。根据 VM,它将是 32 位或 64 位,但它仍然是一个数字。这个数字告诉你对象在内存中。这些数字被称为地址,通常以十六进制格式写成这样0xYYYYYYYY
(这是 32 位地址的示例,64 位地址将是 64 位地址的两倍)。
让我们使用上面的示例,使用 32 位 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
这应该说明引用确实像您在第二个示例中显示的数字一样工作。然而,仅在表面之下,就程序员而言,引用的分配不像原语的分配那样工作。
在 Java 中,您永远不需要担心对象的地址等。在像 C 和 C++ 这样支持较低级别访问的语言中,这变得更加明显和重要。
算术?那么你能做算术和其他你可以用数字做的事情吗?较短的答案是否定的,至少在 java 中没有。
然而,在 C 和 C++ 中,对象指针的递增和递减是完全有效的,并且被大量使用,例如遍历数组。
如果这还不够清楚,请随时提出问题。