Java中说引用传递-这是不准确的

来源:互联网 发布:查看ubuntu详细版本 编辑:程序博客网 时间:2024/05/17 10:25

参考文章:http://www.javaranch.com/campfire/StoryPassBy.jsp

看如下代码:

package test;public class TestReference {int a,b;TestReference(int a,int b){this.a = a ;this.b = b;}static void doTest(TestReference tr){tr = new TestReference(6, 7);System.out.println("doTest中a = "+tr.a);}public static void main(String[] args) {TestReference t = new TestReference(2,3);System.out.println("t修改前a="+t.a);doTest(t);System.out.println("t修改后a="+t.a);}}

运行结果:

t修改前a=2
doTest中a = 6
t修改后a=2

总结:java中只有值传递(pass by value),引用上面英文文章中的原话:

Java is pass-by-value.

For primitives, you pass a copy of the actual value.

For references to objects, you pass a copy of the reference (the remote control).

You never pass the object. All objects are stored on the heap. Always.

Now go have an extra big cup of coffee and write some code.






原创粉丝点击