引用在内存

一 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 。 内存值传递过程如图。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值