简体   繁体   中英

Method Creates new instance

When a method returns an object, does that method automatically create a new instance of that object in memory?

For example:

In Java BigInteger class , I use the add method where num1 , and num2 , lets say, are BigIntegers .

num1.add(num2);

Then I reference it by the same type as in:

BigInteger a = num1.add(num2);

This works and gets the correct data. So the method will create a new instance of that object on the stack?

Just making sure I'm correct about my assumption.

Thanks.

bigInteger.add() does return a new instance, but not all methods do.

What usually returns new object instances that you may run into regularly are:

  • Constructors
  • Factorys/Builders
  • methods operating on immutable objects

BigInteger 's add method says that it returns a BigInteger , doesn't say a new BigInteger , but given that the docs also state that BigInteger is immutable , then you can know it's not returning the this object with a modification, so chances are that it's a new object (I suppose it's possible to be some cached object already representing that state, but even if it was, your usage of BigInteger wouldn't change.).

It depends.

With your BigInteger example, it is returning a new instance of the object.

However with something like StringBuilder, you can do

stringBuilder.append("this").append("is").append("a").append("string");

and each .append(String) is returning the same original object, it just allows you to chain the calls together.

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