JVM如何处理参考变量? [英] How JVM treats reference variables?

查看:63
本文介绍了JVM如何处理参考变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只想知道此陈述是否正确:

Just want to know whether this statement is true or not:

对于这些代码行:

Person Bob = new Person("Bob W.", 30);
System.out.println(Bob.name);

创建一个对象人,并将其内存地址或一种引用发送到引用变量Bob.接下来,当我们调用"Bob.name"时,JVM将查看Bob持有的地址",然后去查看Person对象.然后JVM查看Bob的名字并打印出来!

An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable . Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object. Then JVM looks at Bob's name and prints it!

谢谢!

推荐答案

Java中的所有对象都是通过它们的引用来访问的(不同于原始访问!).变量 bob 是对 Person 类的实例的引用.实例的内存分配/处置将由JVM处理,并且只要存在对该实例的强引用(即 Person bob = new ... ),该实例数据就将由JVM保持活动状态.声明对新创建的 Person 实例的强引用.

All objects in Java are accessed via their references (different from primitive access!). The variable bob is a reference to an instance of the Person class. Memory allocation/disposal of instances will be handled by the JVM, and the instance data will be kept alive by the JVM as long as there exist strong references to that instance (ie Person bob = new ... declares a strong reference to the newly created Person instance).

创建了一个对象人,并将其内存地址或某种引用发送给引用变量Bob

An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable

说已创建Person对象的实例"会更正确,但是可以,Java中用于对象的所有变量都是引用变量.调用 new 将返回对创建实例的引用.可以有许多引用变量指向单个实例.例如,在下面的代码片段中,我们可以有两个指向单个实例的引用:

It would be more correct to say that an "An instance of the Person Object is created", but yes, all variables used for objects in Java are reference variables. Calling new will return the reference to the instance created. There can be many reference variables which point to a single instance. For example, in the following code snippet we can have two references pointing to a single instance:

Person bob = new Person("Bob W.", 30);
Person bob2 = bob;

接下来,当我们调用"Bob.name"时,JVM将查看Bob持有的地址",然后去查看Person对象.

Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object.

完全正确.编译代码后,JVM字节码将使用指令 getfield 来访问 name 字段.该指令需要对象引用和字段引用.在这种情况下, bob.name 将使用 bob 作为 objectref ,并使用 Person#name 作为fieldref .

Exactly. After code is compiled, the JVM bytecode will use the instruction getfield to access the name field. This instruction requires an object reference and the field reference. In this case bob.name will use bob as the objectref and use Person#name as the fieldref.

这篇关于JVM如何处理参考变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆