java java中的对象引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/502256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object reference in java
提问by allan
consider this simple servlet sample:
考虑这个简单的 servlet 示例:
protected void doGet(HttpServletRequest request, HttpServletResponse response){
Cookie cookie = request.getCookie();
// do weird stuff with cookie object
}
I always wonder.. if you modify the object cookie, is it by object or by reference?
我总是想知道..如果你修改对象cookie,是按对象还是按引用?
回答by Zach Scrivena
if you modify the object
cookie, is it by object or by reference?
如果修改对象
cookie,是按对象还是按引用?
Depends on what you mean by "modify" here. If you change the value of the reference, i.e. cookie = someOtherObject, then the original object itself isn't modified; it's just that you lost your reference to it. However, if you change the state of the object, e.g. by calling cookie.setSomeProperty(otherValue), then you are of course modifying the object itself.
取决于您在这里所说的“修改”是什么意思。如果您更改引用的值,即cookie = someOtherObject,则原始对象本身不会被修改;只是你失去了对它的引用。但是,如果您更改对象的状态,例如通过调用cookie.setSomeProperty(otherValue),那么您当然是在修改对象本身。
Take a look at these previous related questions for more information:
查看这些以前的相关问题以获取更多信息:
回答by Kieron
Java methods get passed an object reference by value. So if you change the reference itself, e.g.
Java 方法通过值传递对象引用。因此,如果您更改引用本身,例如
cookie = new MySpecialCookie();
it will not be seen by the method caller. However when you operate on the reference to change the data the object contains:
它不会被方法调用者看到。但是,当您对引用进行操作以更改对象包含的数据时:
cookie.setValue("foo");
then those changes will be visible to the caller.
那么这些更改将对调用者可见。
回答by hhafez
In the following line of code
在以下代码行中
Cookie cookie = request.getCookie(); /* (1) */
the request.getCookie()method is passing a refrence to a Cookieobject.
该request.getCookie()方法正在将引用传递给Cookie对象。
If you later on change cookie bydoing something like
如果你后来改变cookie by做类似的事情
cookie = foo_bar(); /* (2) */
Then you are changing the internal refrence. It in no way affects your original cookieobject in (1)
然后你正在改变内部参考。它绝不会影响cookie(1)中的原始对象
If however you change cookieby doing something like
但是,如果你cookie通过做类似的事情来改变
cookie.setFoo( bar ); /* assuming setFoo changes an instance variable of cookie */
Then you are changing the original object recieved in (1)
然后您正在更改(1)中收到的原始对象
回答by kalyani
object reference is different from object. for eg:
对象引用不同于对象。例如:
class Shape
{
int x = 200;
}
class Shape1
{
public static void main(String arg[])
{
Shape s = new Shape(); //creating object by using new operator
System.out.println(s.x);
Shape s1; //creating object reference
s1 = s; //assigning object to reference
System.out.println(s1.x);
}
}

