简体   繁体   中英

Difference between “passing reference after assigning an object” and “passing object using new keyword” to a method in java?

What difference does it makes?

Let's think we have a method in java as following:

void demoMethod(MyClass mc){
    // some operations
}

First type:

demoMethod(new MyClass()); // directly passing  an object

Second type:

MyClass mc = new MyClass();
demoMethod(mc); // passing reference of an object

No difference in terms of the method's behavior on that reference. The first code can semantically translate to the second one. Eventually, the object created using new MyClass() needs to be stored somewhere so that it can be re-loaded and passed to the method.

However, using the second code you can re-use the reference.

It doesn't make any difference for demoMethod . Actually in both cases you are passing reference only.

However if you want to use the information after demoMethod does some operation in the calling method, you can't do that in first type.

Assume your demoMethod sets a property of your MyClass object to true or false, you don't have any way to find out what it's value is set to.

So, you can do something like

demoMethod(mc);
if(mc.isMyProperty()==true)
   System.out.println("mc is changed");

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