1 如果variable是primitive,那就拷贝原来变量的值到新变量。
2 如果variable是object referece, 那就拷贝原来reference的值到新的变量,所以就有2个reference varibal指向了相同的object.
3. Java passes objects as references and those references are passed by value.
eg.
// Before the method call
Object x = null;
// Start of method call - parameter copying
Object y = x;
// Body of method call
y = "This is a piece of string.";
// End of method call
System.out.println (x);// 什么也没打印
下面看到一段非常形象的解释:
The balloon analogy
I imagine every object as a helium balloon, every reference as a piece of string, and every variable as something which can hold onto a piece of string. If the reference is a null reference, that's like having a piece of string without anything attached to the end. If it's a reference to a genuine object, it's a piece of string tied onto the balloon representing that object. When a reference is copied (either for variable assignment or as part of a method call) it's as if another piece of string is created attached to whatever the first piece of string is attached to. The actual piece of string the variable (if any) is holding onto doesn't go anywhere - it's only copied.
This analogy also explains garbage collection (apart from the java.lang.ref
API, which does "odd" things :) - a balloon floats away unless it is tethered down to something. The balloons can have further holders on them (instance variables), but just because two balloons are holding onto each other doesn't stop them from floating away. (Cyclic references are collected.) Any balloon representing an object which is in the middle of having a method invoked is tethered to the JVM. (Apologies for not being able to phrase that more succinctly - all I mean is that anything in an active thread's stack isn't garbage collected.)
“
那么,到底object的reference variable 是一种什么样的东西呢?有人说这不是C++里面的pointer,有人说其实本质上是的,只是换了个名字。
搜到一篇非常好的blog Java Virtual Machine,说明reference variable 到底是怎样实现的,取决于java virtual machine 的内在机制的具体实现。
第一种实现方式是,在reference中存放object的内存地址,这样中间只需一次中转就可以找到这个object, 但是这样的话,接下来当java virtual machine回收碎片内存的时候,就会很麻烦,你必须更新同一个ojbect的所有相关的referece.
第二种实现方式是,中间增加一层,让reference varibal指向一个中间变量,让这个中间变量指向object 的内存地址,增加了额外的空间来换取方便。
这两种方式的具体解释抄来如下:
Object Representation
The Java virtual machine specification is silent on how objects should be represented on the heap. Object representation--an integral aspect of the overall design of the heap and garbage