引述在内存

引用在内存

一 Java 只会向API提供引用一层的操作。在32位的机器上其中一种引用的实现就是指针。引用不一定要用指针实现,指针也不一定是用直接地址来实现的,这里还是避免用“地址操作”这种说法比较好。
JVM规范说:
3.2 Data Types
The Java virtual machine contains explicit support for objects. An object is either a dynamically allocated class instance or an array. A reference to an object is considered to have Java virtual machine type reference. Values of type reference can be thought of as pointers to objects. More than one reference to an object may exist. Objects are always operated on, passed, and tested via values of type reference.

3.4 Reference Types and Values
There are three kinds of reference types: class types, array types, and interface types. Their values are references to dynamically created class instances, arrays, or class instances or arrays that implement interfaces, respectively. A reference value may also be the special null reference, a reference to no object, which will be denoted here by null. The null reference initially has no runtime type, but may be cast to any type (JLS3 §4.1).
The Java virtual machine specification does not mandate a concrete value encoding null.

在Java的参数传递过程中只传递值,无论是值类型(原始类型)还是引用类型(类的实例或数组)。留意上面引用的3.2里标红的部分,“对象”只能通过“引用的值”来传递,包括变量赋值、参数赋值、返回值。

假设有一个类 class People(){ int i; } 

Object o = new People();  会在初始化两个内存空间。

new People();会初始化堆的一块内存空间(如图HotSpot VM为参考实现)。




















Object o 会在另一块内存空间里(如图)。






二 函数调用过程。

Object o = new People();

void fun(People _peo)
{
_peo.i = 10;
}

fun(o);

System.out.println(o.i);

输出结果为 10 。 内存值传递过程如图。