简体   繁体   中英

In referencing a java object, what is the difference between the two?

I'm fairly new to java. I have a simple question.

public Object getObject() {

//`do something that results to an Object`

return object;

}

1st:

Object object1 = new Object();
object1 = getObject();

2nd:

Object object1 = getObject();

What is the difference between the two? Which is better to use?

它们返回相同的内容(将“;”添加到第一个示例的第一行:P)。

The difference is that in the first case, you are first making a new Object and immediately throwing it away on the next line when you replace it with the result of getObject().

If you modify it slightly, you'll see that the two objects are different instances.

Object object1 = new Object();
System.out.println(object1);
object1 = getObject();
System.out.println(object1);

When you run that, not that the printed value is different. This is because there were two different values assigned to object1.

This is not a pattern you want to be using. All you are doing here is making an object that needs to be garbage collected.

I'm also not sure that case 1 even works. It won't compile, because object is an undefined variable. You would need to change it to return new Object(); That way the value to return is defined.

Really what you want to do is just say Object object = new Object(); Adding the getObject function really isn't buying you anything.

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