gpt4 book ai didi

java - 传递对象引用变量

转载 作者:行者123 更新时间:2023-12-01 11:45:01 24 4
gpt4 key购买 nike

这来自著名的 SCJP Java 书。我的问题是这里的 dim 是如何得到 11 的值的。

import java.awt.Dimension;
class ReferenceTest {
public static void main (String [] args) {
Dimension d = new Dimension(5,10);
ReferenceTest rt = new ReferenceTest();
System.out.println("Before modify() d.height = "+ d.height);
rt.modify(d);
System.out.println("After modify() d.height = "+ d.height);
}
void modify(Dimension dim) {
dim.height = dim.height + 1;
System.out.println("dim = " + dim.height);
}
}

当我们运行这个类时,我们可以看到 modify() 方法确实能够修改第 4 行创建的原始(也是唯一的)Dimension 对象。

C:\Java Projects\Reference>java ReferenceTest
Before modify() d.height = 10
dim = 11
After modify() d.height = 11

请注意,当第 4 行上的 Dimension 对象传递给modify() 方法时,该方法内发生的任何对对象的更改都会针对其引用所传递的对象进行。在前面的示例中,引用变量 d 和 dim 都指向同一个对象。

最佳答案

My question is how does dim get the value of 11 here

暗淡 没有dim.height 确实如此。当代码将 dim 传递到方法中时,传入的值是对对象的引用。然后,该方法会修改该对象的状态(根本不会修改引用),因此调用代码会看到更新后的状态。

这段代码:

Dimension d = new Dimension(5, 10);

在内存中产生类似这样的东西:

+-------------+|      d      |+-------------+     +--------------------+| (reference) |---->| Dimension instance |+-------------+     +--------------------+                    | width: 5           |                    | height: 10         |                    +--------------------+

The variable holds a value that refers to the object elsewhere in memory. You can copy that value (called an object reference), for instance by passing it into a method, but it still refers to the same object.

So when we pass that into modify, during the call to modify, we have:

+-------------+|      d      |+-------------+| (reference) |--++-------------+  |                 |  +--------------------+                 +->| Dimension instance |                 |  +--------------------+                 |  | width: 5           |                 |  | height: 10         |                 |  +--------------------++-------------+  ||     dim     |  |+-------------+  || (reference) |--++-------------+

Now, d and dim each have a copy of the value that tells the JVM where the object is in memory.

This is fundamental to how objects work: The value held by variables, data members, and arguments is a reference to the object, not a copy of it. It's like a number the JVM can use to look up the object elsewhere in memory.

Primitives are actually held inside the variable/data member/argument:

int n = 10;

给我们:

+----+| n  |+----+| 10 |+----+

...但是变量/数据成员/参数不保存对象,它们保存引用对象的值。

关于java - 传递对象引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com