java值传递和引用传递

来源:互联网 发布:做微商好还是淘宝好 编辑:程序博客网 时间:2024/06/01 07:32

java参数传递过程中,传递给方法的参数不管是原始类型还是引用类型,都是它的副本,因此在调用方法中对原始类型的参数做任何操作都不能改变原来参数的值;而对引用类型参数来说,只有改变它的值(setter方法),才能改变原来引用类型变量的值,改变它的地址是不会对原来变量指向的对象内容产生任何影响的。因为引用类型变量不管是原始调用方的还是副本,始终是指向内存里面的同一个对象,所以原始调用方的变量指向的内容不变。
下面是在《Thinking in Java》中的原文:
This brings up the terminology issue, which always seems good for an argument. The term is “pass by value,” and the meaning depends on how you perceive the operation of the program. The general meaning is that you get a local copy of whatever you’re passing, but the real question is how you think about what you’re passing. When it comes to the meaning of “pass by value,” there are two fairly distinct camps:

1.      Java passes everything by value. When you’re passing primitives into a method, you get a distinct copy of the primitive. When you’re passing a handle into a method, you get a copy of the handle. Ergo, everything is pass by value. Of course, the assumption is that you’re always thinking (and caring) that handles are being passed, but it seems like the Java design has gone a long way toward allowing you to ignore (most of the time) that you’re working with a handle. That is, it seems to allow you to think of the handle as “the object, ” since it implicitly dereferences it whenever you make a method call.

2.      Java passes primitives by value (no argument there), but objects are passed by reference. This is the world view that the handle is an alias for the object, so you don’t think about passing handles, but instead say “I’m passing the object.” Since you don’t get a local copy of the object when you pass it into a method, objects are clearly not passed by value. There appears to be some support for this view within Sun, since one of the “reserved but not implemented” keywords is byvalue. (There’s no knowing, however, whether that keyword will ever see the light of day.)

Having given both camps a good airing and after saying “It depends on how you think of a handle,” I will attempt to sidestep the issue for the rest of the book. In the end, it isn’t that important – what is important is that you understand that passing a handle allows the caller’s object to be changed unexpectedly.

原创粉丝点击