这是来自著名的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都指向同一对象。
最佳答案
我的问题是暗淡如何在这里获得11的值dim
不。 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 |
+ ---- +
...但是变量/数据成员/参数不包含对象,它们包含引用对象的值。