您的位置:首页 > 编程语言 > Java开发

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

2013-11-07 21:18 204 查看
参考文章: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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: