简体   繁体   中英

Object reference in java

consider this simple servlet sample:

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?

if you modify the object cookie , is it by object or by reference?

Depends on what you mean by "modify" here. If you change the value of the reference, ie 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, eg by calling cookie.setSomeProperty(otherValue) , then you are of course modifying the object itself.

Take a look at these previous related questions for more information:

Java methods get passed an object reference by value . So if you change the reference itself, eg

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.

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);
    }
}

In the following line of code

Cookie cookie = request.getCookie(); /* (1) */

the request.getCookie() method is passing a refrence to a Cookie object.

If you later on change cookie by doing something like

cookie = foo_bar(); /* (2) */

Then you are changing the internal refrence. It in no way affects your original cookie object in (1)

If however you change cookie by doing something like

cookie.setFoo( bar ); /* assuming setFoo changes an instance variable of cookie */

Then you are changing the original object recieved in (1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM