[英]How JVM treats reference variables?
Just want to know whether this statement is true or not: 只想知道此语句是否正确:
For these lines of code: 对于这些代码行:
Person Bob = new Person("Bob W.", 30);
System.out.println(Bob.name);
An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable . 创建了一个对象人,并将其内存地址或一种引用发送给引用变量Bob。 Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object. 接下来,当我们调用“ Bob.name”时,JVM将查看Bob持有的“地址”,然后去查看Person对象。 Then JVM looks at Bob's name and prints it! 然后JVM查看Bob的名字并打印出来!
Thanks! 谢谢!
All objects in Java are accessed via their references (different from primitive access!). Java中的所有对象都是通过其引用来访问的(不同于原始访问!)。 The variable bob
is a reference to an instance of the Person
class. 变量bob
是对Person
类实例的引用。 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). 实例的内存分配/处理将由JVM处理,并且只要存在对该实例的强引用(即Person bob = new ...
声明对Person bob = new ...
实例的强引用),JVM就会使实例数据保持活动状态。创建的Person
实例)。
An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable 创建一个Object Person,并将其内存地址或某种引用发送给Bob(引用变量)
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. 说“创建了Person对象的实例”会更正确,但是是的,Java中用于对象的所有变量都是引用变量。 Calling new
will return the reference to the instance created. 调用new
将返回对创建实例的引用。 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;
Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object. 接下来,当我们调用“ Bob.name”时,JVM将查看Bob持有的“地址”,然后去查看Person对象。
Exactly. 究竟。 After code is compiled, the JVM bytecode will use the instruction getfield
to access the name
field. 编译代码后,JVM字节码将使用指令getfield
访问name
字段。 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
. 在这种情况下, bob.name
将使用bob
作为objectref
并使用Person#name
作为fieldref
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.